帮我写一个爬取百度图片的python爬虫
时间: 2023-12-31 15:43:28 浏览: 24
以下是一个基本的爬取百度图片的Python爬虫:
```python
import requests
import os
def download_pic(pic_url, save_path):
response = requests.get(pic_url)
with open(save_path, 'wb') as f:
f.write(response.content)
def search_and_download(keyword, download_path):
url = 'https://image.baidu.com/search/index?tn=baiduimage&word={}'.format(keyword)
response = requests.get(url)
pic_urls = response.json()['data']
for i, pic_info in enumerate(pic_urls):
pic_url = pic_info['large_image_url']
save_path = os.path.join(download_path, '{}.jpg'.format(i))
download_pic(pic_url, save_path)
if __name__ == '__main__':
keyword = '猫'
download_path = './download'
if not os.path.exists(download_path):
os.mkdir(download_path)
search_and_download(keyword, download_path)
```
该爬虫首先构造了一个百度图片搜索的URL,然后发送请求获取搜索结果,解析出每张图片的URL,并下载保存到本地。需要注意的是,由于百度图片的URL可能会变化,因此该爬虫并不一定能够一直正常工作。