更新时间:2025-03-27 05:25:49
在数字化时代,从网络获取图片是家常便饭。Python作为编程界的“万金油”,轻松搞定图片下载!今天给大家分享两种实用方法,让你秒变技术小达人👇:
第一招:requests + open
首先用`requests`库发送HTTP请求,获取图片数据,再用`open()`函数以二进制模式写入本地文件。简单代码如下:
```python
import requests
response = requests.get('https://example.com/image.jpg')
with open('image.jpg', 'wb') as f:
f.write(response.content)
```
第二招:urllib模块
无需额外安装库,直接使用Python内置的`urllib`,一步到位!
```python
import urllib.request
urllib.request.urlretrieve('https://example.com/image.jpg', 'image.jpg')
```
两种方式各有千秋,大家可根据需求选择哦!💡无论是保存素材还是批量下载,Python都能帮你高效完成任务。快来试试吧!🚀