1. W1 - requests 库
关键是 requests.get()
函数, 具体可参考:Doc - Requests.
import requests
img_url = 'http://xxx.com/test.jpg'
img_file = 'test.jpg'
response = requests.get(image_url, timeout=3)
if response.status_code == 200: # if response.status_code == requests.codes.ok
with open(img_file, "wb") as fp:
fp.write(response.content)
timeout=3
表示在 3s 后停止请求等待. Requests - Timeouts.
2. W2 - urllib.request 库
import urllib.request
img_url = 'http://xxx.com/test.jpg'
img_file = 'test.jpg'
urllib.request.urlretrieve(img_url, filename=img_file)
3. W3 - wget 库
安装:
pip install wget
import wget
img_url = 'http://xxx.com/test.jpg'
img_file = 'test.jpg'
# 获取文件名
file_name = wget.filename_from_url(img_url)
print(file_name)
# 下载文件, 默认文件名
file_name = wget.download(img_url)
print(file_name)
# 下载文件,指定文件名
file_name = wget.download(img_url, out=img_file)
print(file_name)