我正在编写一个 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 后,我想使用 python 脚本以 pdf 格式保存文件。
这就是我到目前为止所做的。
Code 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()
Code 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
import shutil
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)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)