你能给我写一个python爬取百度图片的编程吗
时间: 2024-04-15 14:27:53 浏览: 15
当然可以!这是一个简单的示例代码,使用Python和第三方库requests和beautifulsoup来爬取百度图片:
```python
import requests
from bs4 import BeautifulSoup
import os
def download_images(url, save_folder):
# 发送请求获取页面内容
response = requests.get(url)
soup = BeautifulSoup(response.content, 'html.parser')
# 创建保存图片的文件夹
if not os.path.exists(save_folder):
os.makedirs(save_folder)
# 查找所有图片链接
img_tags = soup.find_all('img')
for img in img_tags:
img_url = img.get('src')
# 下载图片并保存到文件夹
if img_url.startswith('http'):
response = requests.get(img_url)
img_name = img_url.split('/')[-1]
save_path = os.path.join(save_folder, img_name)
with open(save_path, 'wb') as f:
f.write(response.content)
print(f"已保存图片: {save_path}")
# 输入搜索关键词和要下载的图片数量
search_keyword = input("请输入搜索关键词:")
num_images = int(input("请输入要下载的图片数量:"))
# 构建百度图片搜索url,并发送请求
url = f"https://image.baidu.com/search/index?tn=baiduimage&word={search_keyword}"
response = requests.get(url)
# 解析搜索结果页面并下载图片
if response.status_code == 200:
download_images(url, save_folder=search_keyword)
else:
print("请求失败")
```
请注意,根据百度的使用条款,使用爬虫爬取百度图片可能违反其服务条款。请确保你的爬取行为符合相关法律法规和网站的使用条款。