Python 中保存爬取的图片有三种方法:使用 urllib.request 模块的 urlretrieve() 函数直接下载图片。使用 requests 库的 get() 方法下载图片并使用 open() 函数写入文件。使用第三方库(如 Beautiful Soup 或 Scrapy)获取图片 URL 后,再使用上述方法保存图片。

如何在 Python 中保存爬取的图片
方法 1:使用 urllib.request
<code class="python">import urllib.request url = 'https://example.com/image.jpg' urllib.request.urlretrieve(url, 'image.jpg')</code>
方法 2:使用 requests
<code class="python">import requests
url = 'https://example.com/image.jpg'
response = requests.get(url)
with open('image.jpg', 'wb') as f:
f.write(response.content)</code>方法 3:使用第三方库
立即学习“Python免费学习笔记(深入)”;
示例(使用 Beautiful Soup):
<code class="python">from bs4 import BeautifulSoup
html_content = '''<img src="https://example.com/image.jpg">'''
soup = BeautifulSoup(html_content, 'html.parser')
image_url = soup.find('img')['src']
urllib.request.urlretrieve(image_url, 'image.jpg')</code>以上就是Python怎么保存爬虫图片的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号