Python中如何下载图片?
时间: 2024-03-21 19:36:02 浏览: 19
在Python中,你可以使用`urllib`或者`requests`来下载图片。下面是使用`urllib`库的示例代码:
```python
import urllib.request
def download_image(url, save_path):
urllib.request.urlretrieve(url, save_path)
# 调用示例
image_url = "https://example.com/image.jpg"
save_path = "path/to/save/image.jpg"
download_image(image_url, save_path)
```
在上面的代码中,`download_image`函数接受两个参数:图片的URL和保存路径。它使用`urllib.request.urlretrieve`函数来下载图片并保存到指定的路径。
如果你更喜欢使用`requests`库,可以使用以下示例代码:
```python
import requests
def download_image(url, save_path):
response = requests.get(url)
with open(save_path, "wb") as file:
file.write(response.content)
# 调用示例
image_url = "https://example.com/image.jpg"
save_path = "path/to/save/image.jpg"
download_image(image_url, save_path)
```
在上面的代码中,`download_image`函数使用`requests.get`方法发送GET请求获取图片的内容,并使用`open`函数将内容写入到指定的文件路径中。