Python中可以使用requests库来下载文件。Requests库是一个简单易用的HTTP库,它支持HTTP的GET、POST、PUT、DELETE等请求方式,并且支持SSL认证、自动跳转、cookie等特性,可以实现文件下载、网页爬虫等功能。下面给出一个使用requests库下载文件的示例:
安装requests库
pip install requests
使用requests下载文件
import requests url = 'http://example.com/file.zip' # 下载文件 r = requests.get(url) # 将文件写入本地 with open('file.zip', 'wb') as f: f.write(r.content)
上面的代码中,使用requests.get()方法发送GET请求,使用open()方法将文件写入本地。
使用requests下载文件并设置超时时间
import requests url = 'http://example.com/file.zip' # 下载文件并设置超时时间 r = requests.get(url, timeout=10) # 将文件写入本地 with open('file.zip', 'wb') as f: f.write(r.content)
上面的代码中,使用requests.get()方法发送GET请求,并设置超时时间为10秒,使用open()方法将文件写入本地。
使用requests下载文件并设置HTTP请求头
import requests url = 'http://example.com/file.zip' # 设置HTTP请求头 headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36' } # 下载文件 r = requests.get(url, headers=headers) # 将文件写入本地 with open('file.zip', 'wb') as f: f.write(r.content)
上面的代码中,使用字典定义HTTP请求头,使用requests.get()方法发送GET请求,并将请求头作为参数传入,使用open()方法将文件写入本地。
本文介绍了使用Python的requests库下载文件的方法和示例。可以使用requests.get()方法发送GET请求,并使用open()方法将文件写入本地,还可以设置超时时间和HTTP请求头。