我正在尝试使用以下Python函数下载pdf文件。我能够在浏览器中打开URL(重定向到另一个URL)。但是代码出现了404错误。
import requests
def downloadFile(url, fileName):
r = requests.get(url, allow_redirects=True, stream=True)
with open(fileName, "wb") as pdf:
for chunk in r.iter_content(chunk_size=1024):
if chunk:
pdf.write(chunk)
downloadFile("http://pubs.vmware.com/vsphere-55/topic/com.vmware.ICbase/PDF/vsphere-esxi-vcenter-server-552-storage-guide.pdf", "vsphere-esxi-vcenter-server-552-storage-guide.pdf")
答案 0 :(得分:2)
很少有网站根据语言或位置进行屏蔽。以下代码附加标题工作
In [11]: def downloadFile(url, fileName):
headers = {'Accept-Language': 'en-US,en;q=0.9,te;q=0.8'}
r = requests.get(url, allow_redirects=True, stream=True, headers=headers)
with open(fileName, "wb") as pdf:
for chunk in r.iter_content(chunk_size=1024):
if chunk:
pdf.write(chunk)
In [12]: downloadFile("http://pubs.vmware.com/vsphere-55/topic/com.vmware.ICbase/PDF/vsphere-esxi-vcenter-server-552-storage-guide.pdf", "vsphere-esxi-vcenter-server-552-storage-guide.pdf")