【发布时间】:2016-02-02 23:02:01
【问题描述】:
我正在编写一个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 格式。
这是我到目前为止所做的。
代码 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()
代码 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
如果我使用 Code 2,我如何传递授权细节?
【问题讨论】:
-
您想要使用
webbrowser.open、requests.get或urllib2.urlopen的解决方案吗? -
@Robᵩ - 我已经尝试过上述方法。所以 requests 或 urllib2 任何东西都可以工作。
标签: python python-2.7 url pdf pdf-generation