如何使用 Requests 在线解码 pdf 中的文本?

Jam*_*ard 4 python python-3.x python-requests

我正在尝试从澳大利亚证券交易所网站创建一个 pdf puller,这将允许我搜索公司发布的所有“公告”,并在这些公告的 pdf 文件中搜索关键词。

到目前为止我所做的是使用请求库。以下是我到目前为止的代码:

import requests

url = 'http://www.asx.com.au/asxpdf/20171103/pdf/43nyyw9r820c6r.pdf'
response = requests.get(url)

print(response.content)
Run Code Online (Sandbox Code Playgroud)

然而,打印的是以下字符串(我将把它剪掉,因为它太长了):

> b'%PDF-1.5\r%\xe2\xe3\xcf\xd3\r\n5 0 obj\r<</E 212221/H [ 1081 145 ]/L
> 212973/Linearized 1/N 1/O 8/T 212553>>\rendobj\r                      
> \r\r42 0 obj\r<</DecodeParms <</Columns 5/Predictor 12>>/Encrypt 7 0
> R/Filter /FlateDecode/ID [(\\216\\203\\217T\\n\\f\\236\\345?%\\214t4
> E\\271) (\\216\\203\\217T\\n\\f\\236\\345?%\\214t4 E\\271)]/Index [5
> 38]/Info 3 0 R/Length 86/Prev 212554/Root 6 0 R/Size 43/Type /XRef/W
> [1 3
> 1]>>\rstream\nx\x9ccbd`\x10``b``:\x04"\x19\xab\xc1d-X\xc4\x06D2\xac\x02\xb3\x93\xc0\xe2\x1d
> \x92?\x07,\x1e\t"\xb9T\x80$\xe3\x84\xcb@\x92\xa9m"\x03\x13\xe3\xdf\x13Z`Y\x06\xc6\x01#\xff3\xb0h\xbcfb`\xb6\x12\x02\xba\xe4\xef!S\x06\x0
Run Code Online (Sandbox Code Playgroud)

我已经搜索了 stackexchange 和其他网站几天,并尝试使用print(response.content.decode('utf-8')ascii,但它们都不是我能阅读的任何内容。

很抱歉,我知道很明显我是个菜鸟,但任何帮助将不胜感激!

非常感谢。

DRP*_*RPK 8

PDF 文件是二进制模式,您应该将其作为带有页眉和页脚的格式来阅读。您不能将 bianry 文件作为原始字符串读取。

1) 如果您的文件名中有任何空格,那么尽管返回成功代码,PyPDF 2 解密功能最终还是会失败。在通过 PyPDF2 运行 PDF 之前,在命名 PDF 时尽量坚持使用下划线。

例如,而不是“我的pdf.pdf”做类似“my_pdf.pdf”的事情。

2)尝试使用空字符串作为密码解密它,它可以工作。

尝试这个 :

import requests, PyPDF2


url = 'http://www.asx.com.au/asxpdf/20171103/pdf/43nyyw9r820c6r.pdf'
response = requests.get(url)
my_raw_data = response.content

with open("my_pdf.pdf", 'wb') as my_data:
    my_data.write(my_raw_data)

open_pdf_file = open("my_pdf.pdf", 'rb')
read_pdf = PyPDF2.PdfFileReader(open_pdf_file)
if read_pdf.isEncrypted:
    read_pdf.decrypt("")
    print(read_pdf.getPage(0).extractText())

else:
    print(read_pdf.getPage(0).extractText())
Run Code Online (Sandbox Code Playgroud)