在Python中,爬虫保存图片通常有以下几种方法:
1. 使用`requests`库:
import requests
url = 'http://example.com/image.jpg' 替换为实际的图片URL
response = requests.get(url)
if response.status_code == 200: 检查响应状态码
with open('image.jpg', 'wb') as f: 使用二进制模式打开文件
f.write(response.content) 将图片数据写入本地文件
2. 使用`urllib.request`模块的`urlretrieve()`函数:
import urllib.request
url = 'http://example.com/image.jpg' 替换为实际的图片URL
urllib.request.urlretrieve(url, 'image.jpg') 下载图片并保存为image.jpg
3. 使用第三方库如`beautfulsoup4`结合`requests`:
from bs4 import BeautifulSoup
import requests
url = 'http://example.com' 替换为实际的网页URL
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
img_tag = soup.find('img') 查找图片标签
img_url = img_tag['src'] 获取图片URL
response = requests.get(img_url)
if response.status_code == 200:
with open('image.jpg', 'wb') as f:
f.write(response.content)
请根据实际需要选择合适的方法,并确保遵循网站的版权和使用规定。