Python爬虫脚本:根据关键词从hellorf网站抓取图片
下面是一个根据给定关键词列表爬取指定网站图片的Python爬虫脚本:
from selenium import webdriver
from selenium.webdriver.common.by import By
import requests
import os
# 设置关键词列表
keywords = ['自拍']
# 初始化Chrome Driver
driver = webdriver.Chrome()
# 打开网站地址
url = 'https://www.hellorf.com/image/search?q=' + '%20'.join(keywords)
driver.get(url)
# 获取文章链接列表
article_urls = driver.find_elements(By.CSS_SELECTOR, 'a')
article_urls = [article_url.get_attribute('href') for article_url in article_urls if '_blank' in article_url.get_attribute('target')]
article_urls = [article_url for article_url in article_urls if 'www.hellorf.com/image/show/' in article_url]
# 遍历文章链接列表
for article_url in article_urls:
# 打开文章链接
driver.get(article_url)
# 获取图片链接
image_urls = driver.find_elements(By.CSS_SELECTOR, 'img')
image_urls = [image_url.get_attribute('src') for image_url in image_urls]
# 下载图片
for image_url in image_urls:
response = requests.get(image_url)
if response.status_code == 200:
# 获取文件名
filename = os.path.basename(image_url)
# 保存图片
with open(filename, 'wb') as f:
f.write(response.content)
print(f'Saved image: {filename}')
else:
print(f'Failed to download image: {image_url}')
# 关闭浏览器
driver.quit()
请注意,上述代码使用了Selenium库来模拟浏览器操作,并使用了Requests库来下载图片。在运行脚本之前,请确保你已经安装了这两个库。另外,由于Selenium需要驱动程序(如ChromeDriver)来与浏览器交互,你需要根据你的实际情况下载并配置适合你的驱动程序。
原文地址: http://www.cveoy.top/t/topic/pDoQ 著作权归作者所有。请勿转载和采集!