Download and save PDF file with Python requests module

I am trying to download a PDF file from a website and save it to disk. My attempts either fail with encoding errors or result in blank PDFs.

In [1]: import requests


In [2]: url = 'http://www.hrecos.org//images/Data/forweb/HRTVBSH.Metadata.pdf'


In [3]: response = requests.get(url)


In [4]: with open('/tmp/metadata.pdf', 'wb') as f:
...:     f.write(response.text)
---------------------------------------------------------------------------
UnicodeEncodeError                        Traceback (most recent call last)
<ipython-input-4-4be915a4f032> in <module>()
1 with open('/tmp/metadata.pdf', 'wb') as f:
----> 2     f.write(response.text)
3


UnicodeEncodeError: 'ascii' codec can't encode characters in position 11-14: ordinal not in range(128)


In [5]: import codecs


In [6]: with codecs.open('/tmp/metadata.pdf', 'wb', encoding='utf8') as f:
...:     f.write(response.text)
...:

I know it is a codec problem of some kind but I can't seem to get it to work.

219613 次浏览

在这种情况下,应该使用 response.content:

with open('/tmp/metadata.pdf', 'wb') as f:
f.write(response.content)

来自 the document:

对于非文本请求,您还可以以字节形式访问响应正文:

>>> r.content
b'[{"repository":{"open_issues":0,"url":"https://github.com/...

这意味着: response.text以字符串对象的形式返回输出,在下载 文本文件时使用它。如 HTML 文件等。

response.content将输出作为字节对象返回,在下载 二进制文件时使用它。如 PDF 文件、音频文件、图像等。


您也可以使用 response.raw代替 。但是,如果要下载的文件很大,则使用它。下面是一个基本的例子,你也可以在文件中找到:

import requests


url = 'http://www.hrecos.org//images/Data/forweb/HRTVBSH.Metadata.pdf'
r = requests.get(url, stream=True)


with open('/tmp/metadata.pdf', 'wb') as fd:
for chunk in r.iter_content(chunk_size):
fd.write(chunk)

chunk_size是要使用的块大小。如果将其设置为 2000,那么请求将下载该文件的第一个 2000字节,并将它们写入文件,然后一遍又一遍地执行此操作,直到完成为止。

这样可以节省内存。但是在这种情况下我更喜欢使用 response.content,因为您的文件很小。正如您可以看到的使用 response.raw是复杂的。


相关资料:

关于凯文答案写在 tmp文件夹里,应该是这样的:

with open('./tmp/metadata.pdf', 'wb') as f:
f.write(response.content)

他忘记了 .之前的地址,当然你的文件夹 tmp应该已经创建

在 Python3中,我发现 pathlib 是实现这一点的最简单方法。Request 的 response.content与 pathlib 的 write _ byte 很好地结合在一起。

from pathlib import Path
import requests
filename = Path('metadata.pdf')
url = 'http://www.hrecos.org//images/Data/forweb/HRTVBSH.Metadata.pdf'
response = requests.get(url)
filename.write_bytes(response.content)

请注意,我是个初学者。如果我的解决方案是错误的,请随时更正和/或让我知道。我可能也会学到一些新的东西。

我的解决办法是:

相应地将 downloadPath 更改为保存文件的位置。也可以随意使用绝对路径。

Save the below as downloadFile.py.

用法: python downloadFile.py url-of-the-file-to-download new-file-name.extension

记住要加一个扩展!

示例用法: python downloadFile.py http://www.google.co.uk google.html

import requests
import sys
import os


def downloadFile(url, fileName):
with open(fileName, "wb") as file:
response = requests.get(url)
file.write(response.content)




scriptPath = sys.path[0]
downloadPath = os.path.join(scriptPath, '../Downloads/')
url = sys.argv[1]
fileName = sys.argv[2]
print('path of the script: ' + scriptPath)
print('downloading file to: ' + downloadPath)
downloadFile(url, downloadPath + fileName)
print('file downloaded...')
print('exiting program...')

你可以使用 urllib:

import urllib.request
urllib.request.urlretrieve(url, "filename.pdf")

一般来说,这应该可以在 Python 3中工作:

import urllib.request
..
urllib.request.get(url)

记住,在 Python 2之后,urllib 和 urllib2不能正常工作。

如果在某些神秘的情况下请求不起作用(发生在我身上) ,您也可以尝试使用

wget.download(url)

相关阅读:

这里有一个不错的解释/解决方案,可以在网页上查找和下载所有 pdf 文件:

Https://medium.com/@dementorwriter/notesdownloader-use-web-scraping-to-download-all-pdfs-with-python-511ea9f55e48