我正在编写一个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
如果我使用代码2,我如何传递授权详细信息?
我认为这会起作用,你可以将身份验证传递到requests.get ...然后将原始内容写入新的pdf文件
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)
您可以这样做的一种方法是:
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)
你可以尝试这样的事情:
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()):
对于某些文件 - 至少 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 (或者您可以通过解析子进程错误来确定下载是否成功消息)。