如何使用python通过https下载pdf文件
我正在编写一个python脚本,它将根据URL中给定的格式在本地保存pdf文件。例如如何使用python通过https下载pdf文件,python,python-2.7,url,pdf,pdf-generation,Python,Python 2.7,Url,Pdf,Pdf Generation,我正在编写一个python脚本,它将根据URL中给定的格式在本地保存pdf文件。例如 https://Hostname/saveReport/file_name.pdf #saves the content in PDF file. 我正在通过python脚本打开此URL: import webbrowser webbrowser.open("https://Hostname/saveReport/file_name.pdf") url包含大量图像和文本打开此URL后,我希望使用
https://Hostname/saveReport/file_name.pdf #saves the content in PDF file.
我正在通过python脚本打开此URL:
import webbrowser
webbrowser.open("https://Hostname/saveReport/file_name.pdf")
url包含大量图像和文本打开此URL后,我希望使用python脚本以pdf格式保存文件。
这就是我到目前为止所做的。代码1: 代码2:
import urllib2
import ssl
url="https://Hostname/saveReport/file_name.pdf"
context = ssl._create_unverified_context()
response = urllib2.urlopen(url, context=context) #How should i pass authorization details here?
html = response.read()
在上面的代码中,我得到:urllib2.HTTPError:HTTP Error 401:Unauthorized
如果使用代码2,如何传递授权详细信息?您可以尝试以下方法:
import requests
response = requests.get('https://websitewithfile.com/file.pdf',verify=False, auth=('user', 'pass'))
with open('file.pdf','w') as fout:
fout.write(response.read()):
我想这会管用的
import requests
url="https://Hostname/saveReport/file_name.pdf" #Note: It's https
r = requests.get(url, auth=('usrname', 'password'), verify=False,stream=True)
r.raw.decode_content = True
with open("file_name.pdf", 'wb') as f:
shutil.copyfileobj(r.raw, f)
一种方法是:
import urllib3
urllib3.disable_warnings()
url = r"https://websitewithfile.com/file.pdf"
fileName = r"file.pdf"
with urllib3.PoolManager() as http:
r = http.request('GET', url)
with open(fileName, 'wb') as fout:
fout.write(r.data)
对于某些文件-至少tar归档文件(甚至所有其他文件),您可以使用pip:
import sys
from subprocess import call, run, PIPE
url = "https://blabla.bla/foo.tar.gz"
call([sys.executable, "-m", "pip", "download", url], stdout=PIPE, stderr=PIPE)
但是您应该以其他方式确认下载成功,因为pip会对任何不包含setup.py的存档文件产生错误,因此stderr=PIPE(或者您可以通过解析子进程错误消息来确定下载是否成功)。是否要使用
webbrowser.open
,请求.get
,或urllib2.urlopen
?@Robᵩ - 我尝试过以上方法。因此,请求或urllib2任何东西都可以工作。response.text
可能是一个错误的选择,因为它涉及解码步骤。也许用wb
打开文件,然后写response.content
而不是.response.raw,我认为显然,response.iter\u chunk
是request
的“首选和推荐的检索文档的方式”:我用一种更好的方式来获取响应内容
import sys
from subprocess import call, run, PIPE
url = "https://blabla.bla/foo.tar.gz"
call([sys.executable, "-m", "pip", "download", url], stdout=PIPE, stderr=PIPE)