I am writing a python script, which will save pdf file locally according to the format given in URL. for eg.
我正在编写一个python脚本,它将根据URL中给出的格式在本地保存pdf文件。如。
https://Hostname/saveReport/file_name.pdf #saves the content in PDF file.
I am opening this URL through python script :
我正在通过python脚本打开这个URL:
import webbrowser
webbrowser.open("https://Hostname/saveReport/file_name.pdf")
The url contains lots of images and text. Once this URL is opened i want to save a file in pdf format using python script.
该url包含大量图像和文本。打开这个URL后,我想使用python脚本以pdf格式保存文件。
This is what i have done so far.
Code 1:
这就是我到目前为止所做的。代码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:
代码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()
In above code i am getting: urllib2.HTTPError: HTTP Error 401: Unauthorized
在上面的代码中,我得到:urllib2。HTTPError: HTTP错误401:未授权
If i use Code 2, how can i pass authorization details?
如果使用代码2,如何传递授权细节?
3 个解决方案
#1
6
I think this will work
我想这行得通
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)
#2
0
You can try something like :
你可以试试:
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()):
#3
0
One way you can do that is:
一种方法是:
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)
#1
6
I think this will work
我想这行得通
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)
#2
0
You can try something like :
你可以试试:
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()):
#3
0
One way you can do that is:
一种方法是:
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)