是的,Python的requests库可以用于抓取图片。要抓取图片,你需要发送一个HTTP GET请求到图片的URL,然后使用Python的BytesIO对象来处理返回的二进制数据。以下是一个简单的示例:
import requests
from io import BytesIO
def download_image(url, save_path):
response = requests.get(url)
if response.status_code == 200:
with open(save_path, 'wb') as f:
f.write(response.content)
print(f"Image downloaded successfully and saved to {save_path}")
else:
print(f"Failed to download image, status code: {response.status_code}")
image_url = "https://example.com/image.jpg"
save_path = "image.jpg"
download_image(image_url, save_path)
这个示例中,download_image
函数接受一个图片的URL和保存路径,然后使用requests库发送GET请求。如果请求成功(HTTP状态码为200),它将图片数据保存到指定的文件路径。