python爬取图片的代码
时间: 2025-01-06 08:30:59 浏览: 0
在Python中,你可以使用requests库来发送HTTP请求获取图片,然后使用BeautifulSoup或者PIL(Python Imaging Library)来处理HTML内容并下载图片。下面是一个简单的示例,假设你想从网页上爬取一张图片:
```python
import requests
from bs4 import BeautifulSoup
import os
def download_image(url):
# 发送GET请求
response = requests.get(url)
# 检查请求是否成功
if response.status_code == 200:
# 解析响应内容为BeautifulSoup对象
soup = BeautifulSoup(response.content, 'html.parser')
# 找到图片标签,通常可能是<img>标签
img_tag = soup.find('img') or soup.find('figure', {'class': 'image'}) # 根据网站结构调整
# 获取图片URL
img_url = img_tag['src'] if 'src' in img_tag.attrs else None
# 下载图片
if img_url:
response_img = requests.get(img_url)
filename = os.path.basename(img_url)
with open(filename, 'wb') as f:
f.write(response_img.content)
print(f"图片'{filename}'已下载")
else:
print("未找到图片链接")
else:
print(f"请求失败,状态码:{response.status_code}")
# 使用函数并提供目标网址
download_image('http://example.com/your-image-url-here')
```
阅读全文