python爬虫爬取百度照片代码
时间: 2025-06-13 13:46:49 浏览: 15
### 使用Python编写爬虫抓取百度图片
为了实现从百度图片页面抓取图像的功能,下面提供了一个简化版的代码示例。需要注意的是,在执行此类操作前应当查阅并遵循目标网站的服务条款以及`robots.txt`文件中的规定。
```python
import os
from urllib.parse import unquote, urlparse
import requests
from bs4 import BeautifulSoup
def download_image(image_url, save_path='./images'):
try:
if not os.path.exists(save_path):
os.makedirs(save_path)
img_data = requests.get(image_url).content
file_name = os.path.join(save_path, image_url.split('/')[-1])
with open(file_name, 'wb') as handler:
handler.write(img_data)
print(f'Successfully downloaded {file_name}')
except Exception as e:
print('Failed to download:', str(e))
url = "https://image.baidu.com/search/index?tn=baiduimage&ps=1&ct=201326592"\
"&lm=-1&cl=2&nc=1&ie=utf-8&word=%E7%BE%8E%E9%A3%9F"
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
img_tags = soup.find_all('img')
for index, img_tag in enumerate(img_tags[:5]): # 只下载前五张作为示范
src = img_tag['src']
parsed_uri = urlparse(src)
domain = '{uri.scheme}://{uri.netloc}/'.format(uri=parsed_uri)
full_img_url = unquote(domain + src.replace('//', '/'))
download_image(full_img_url)
```
此脚本通过向百度图片搜索页面发送GET请求来获取HTML文档,并利用BeautifulSoup解析其中所有的`<img>`标签以提取图片链接。之后调用自定义函数`download_image()`保存这些资源到本地磁盘上指定位置[^2]。
由于网络环境复杂多变加上反爬机制的存在,上述方法可能无法适用于所有场景;对于动态加载的数据或更复杂的交互逻辑,则需借助Selenium或其他工具模拟浏览器行为完成任务[^3]。
阅读全文
相关推荐


















