用python爬取百度图片
时间: 2023-05-27 16:06:33 浏览: 61
以下是一个简单的Python程序,使用selenium和beautifulsoup库来爬取百度图片。
```python
from selenium import webdriver
from bs4 import BeautifulSoup
import urllib.request
# 搜索关键字
search_key = "猫"
# 设置浏览器驱动
driver = webdriver.Chrome()
# 打开百度图片搜索页面
driver.get("https://image.baidu.com/")
# 找到搜索框并输入关键字
search_box = driver.find_element_by_xpath('//*[@id="kw"]')
search_box.send_keys(search_key)
# 找到搜索按钮并点击
search_button = driver.find_element_by_xpath('//*[@id="homeSearchForm"]/div/div[1]/button')
search_button.click()
# 等待页面加载完成
driver.implicitly_wait(5)
# 找到图片列表
soup = BeautifulSoup(driver.page_source, "html.parser")
img_list = soup.find_all('img', class_='main_img')
# 下载图片
for i, img in enumerate(img_list):
img_url = img['src']
urllib.request.urlretrieve(img_url, f"{search_key}_{i}.jpg")
# 关闭浏览器
driver.quit()
```
这个程序使用selenium模拟浏览器行为来搜索并加载页面,然后使用beautifulsoup库来解析页面,找到图片列表。最后,使用urllib库来下载每个图片。下载的图片将保存在程序运行的当前目录中,并使用关键字和序号命名。