背景,pdf或其他格式文件从网页(包括其他存储,比如AWS的S3,阿里的OSS等)下载,可以用如下方法:
1. 使用 requests 模块requests 是一个广泛使用的HTTP客户端库,
可以方便地下载各种类型的文件:import requests
def download_file_with_requests(url, local_filename=None):
# 如果没有指定本地文件名,则默认使用URL的最后一部分作为文件名
if local_filename is None:
local_filename = url.split('/')[-1]
response = requests.get(url, stream=True)
# 检查响应状态码是否正常(例如200表示成功)
if response.status_code == 200:
with open(local_filename, 'wb') as f:
for chunk in response.iter_content(chunk_size=1024):
if chunk: # filter out keep-alive new chunks
f.write(chunk)
return local_filename
else:
raise Exception(f"Unable to download file, server responded with status code: {response.status_code}")
# 使用示例
url = 'http://example.com/somefi