12 python pdf url pdf-generation python-2.7
我正在编写一个python脚本,它将根据URL中给出的格式在本地保存pdf文件.例如.
https://Hostname/saveReport/file_name.pdf #saves the content in PDF file.
Run Code Online (Sandbox Code Playgroud)
我通过python脚本打开这个URL:
import webbrowser
webbrowser.open("https://Hostname/saveReport/file_name.pdf")
Run Code Online (Sandbox Code Playgroud)
网址包含大量图片和文字.打开此URL后,我想使用python脚本以pdf格式保存文件.
这就是我到目前为止所做的.
代码1:
import requests
url="https://Hostname/saveReport/file_name.pdf" #Note: It's https
r = requests.get(url, auth=('usrname', 'password'), verify=False)
file = open("file_name.pdf", 'w')
file.write(r.read())
file.close()
Run Code Online (Sandbox Code Playgroud)
代码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()
Run Code Online (Sandbox Code Playgroud)
在上面的代码我得到:urllib2.HTTPError:HTTP错误401:未经授权
如果我使用代码2,我如何通过授权详细信息?
我认为这会奏效
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)
Run Code Online (Sandbox Code Playgroud)