如何使用python通过https下载pdf文件 [英] How do i download pdf file over https with python

查看:1337
本文介绍了如何使用python通过https下载pdf文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个python脚本,它将根据URL中提供的格式在本地保存pdf文件.例如

I am writing a python script, which will save pdf file locally according to the format given in URL. for eg.

https://Hostname/saveReport/file_name.pdf   #saves the content in PDF file.

我正在通过python脚本打开此URL:

I am opening this URL through python script :

 import webbrowser
 webbrowser.open("https://Hostname/saveReport/file_name.pdf")  

URL中包含许多图像和文本. 打开此URL后,我想使用python脚本将文件保存为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.

这是我到目前为止所做的.
代码1:

This is what i have done so far.
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()

代码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错误401:未经授权

In above code i am getting: urllib2.HTTPError: HTTP Error 401: Unauthorized

如果我使用代码2,如何传递授权详细信息?

If i use Code 2, how can i pass authorization details?

推荐答案

我认为这会起作用

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)      

这篇关于如何使用python通过https下载pdf文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆