Python中如何使用下载器(Downloader)下载网络上的图片
发布时间:2023-12-17 13:06:16
在Python中,可以使用多个库来下载网络上的图片,例如urllib,requests和beautifulsoup等。下面是其中两个常用的库的使用例子:
1. 使用urllib库下载网络上的图片:
import urllib.request
def download_image(url, save_path):
try:
urllib.request.urlretrieve(url, save_path)
print("Image downloaded successfully!")
except Exception as e:
print("Error occurred while downloading image:", str(e))
# 使用示例
url = "https://example.com/image.jpg"
save_path = "path/to/save/image.jpg"
download_image(url, save_path)
通过urllib库的urlretrieve()函数可以下载图片,并将其保存到指定的路径。如果下载成功,则会打印"Image downloaded successfully!";如果出现错误,则会打印错误消息。
2. 使用requests库下载网络上的图片:
import requests
def download_image(url, save_path):
try:
response = requests.get(url, stream=True)
response.raise_for_status()
with open(save_path, "wb") as f:
for chunk in response.iter_content(chunk_size=8192): # 每次下载8KB数据
f.write(chunk)
print("Image downloaded successfully!")
except Exception as e:
print("Error occurred while downloading image:", str(e))
# 使用示例
url = "https://example.com/image.jpg"
save_path = "path/to/save/image.jpg"
download_image(url, save_path)
使用requests库的get()函数可以发送请求并获取响应。stream=True参数可以确保将文件流保存到磁盘而不是一次性将整个文件加载到内存中。然后,我们可以使用iter_content(chunk_size)函数逐块写入文件,chunk_size参数指定了每次下载的数据块大小。如果下载成功,则会打印"Image downloaded successfully!";如果出现错误,则会打印错误消息。
这是两种常用的下载网络上的图片的方法。根据不同的需求和使用场景,你可以选择使用不同的库和函数来实现图片下载。
