python如何爬取图片到指定文件夹_python网络爬虫爬取图片

python如何爬取图片到指定文件夹_python网络爬虫爬取图片在 Python 中 爬虫保存图片通常有以下几种方法 1 使用 requests 库 pythonimport requests url http example com image jpg 替换为实际的图片 URLresponse requests get url if response status code 200 检查响应状态码 with

在Python中,爬虫保存图片通常有以下几种方法:

1. 使用`requests`库:

python

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()`函数:

python

import urllib.request

url = 'http://example.com/image.jpg' 替换为实际的图片URL

urllib.request.urlretrieve(url, 'image.jpg') 下载图片并保存为image.jpg

3. 使用第三方库如`beautfulsoup4`结合`requests`:

python

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)

请根据实际需要选择合适的方法,并确保遵循网站的版权和使用规定。

编程小号
上一篇 2026-03-20 09:06
下一篇 2026-03-20 09:02

相关推荐

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://sigusoft.com/bj/70996.html