用python爬虫爬取百度的网页图片
时间: 2023-12-31 17:17:59 浏览: 32
您可以使用Python的requests模块和BeautifulSoup模块来实现这个任务。首先,使用requests模块发起请求获取百度图片页面内容,然后使用BeautifulSoup模块解析html页面内容,从中提取图片的URL,并使用requests模块下载图片保存到本地。
以下是实现代码示例:
```python
import requests
from bs4 import BeautifulSoup
url = 'https://image.baidu.com/search/index?tn=baiduimage&word=python'
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'}
response = requests.get(url, headers=headers)
soup = BeautifulSoup(response.text, 'html.parser')
img_tags = soup.find_all('img')
img_urls = [img['src'] for img in img_tags]
for i, url in enumerate(img_urls):
response = requests.get(url)
with open(f"python_img_{i}.jpg", "wb") as f:
f.write(response.content)
```
这段代码可以爬取百度图片搜索结果中与关键字 "python" 相关的所有图片,并将它们保存在本地。