Python3从web解析PDF

Python3从web解析PDF,python,pdf,python-requests,pypdf2,Python,Pdf,Python Requests,Pypdf2,我试着从一个网页上获取一个PDF文件,解析它,然后用打印机将结果打印到屏幕上。我使用以下代码使其正常工作: with open("foo.pdf", "wb") as f: f.write(requests.get(buildurl(jornal, date, page)).content) pdfFileObj = open('foo.pdf', "rb") pdf_reader = PyPDF2.PdfFileReader(pdfFileObj) page_obj = pdf_rea

我试着从一个网页上获取一个PDF文件,解析它,然后用打印机将结果打印到屏幕上。我使用以下代码使其正常工作:

with open("foo.pdf", "wb") as f:
    f.write(requests.get(buildurl(jornal, date, page)).content)
pdfFileObj = open('foo.pdf', "rb")
pdf_reader = PyPDF2.PdfFileReader(pdfFileObj)
page_obj = pdf_reader.getPage(0)
print(page_obj.extractText())
写一个文件,这样我就可以读了,虽然听起来很浪费,所以我想我应该用这个来减少中间人的工作量:

pdf_reader = PyPDF2.PdfFileReader(requests.get(buildurl(jornal, date, page)).content)
page_obj = pdf_reader.getPage(0)
print(page_obj.extractText())

但是,这会产生一个
AttributeError:“bytes”对象没有属性“seek”
。如何将来自
请求的PDF直接输入PyPDF2?

使用io来伪造文件的使用(Python 3):

我没有在您的上下文中进行测试,但我测试了这个简单的示例,它成功了:

import io

output = io.BytesIO()
output.write(bytes("hello world","ascii"))
output.seek(0)
print(output.read())
收益率:

b'hello world'

您必须使用
BytesIO
将返回的
内容转换为类似文件的对象:

import io

pdf_content = io.BytesIO(requests.get(buildurl(jornal, date, page)).content)
pdf_reader = PyPDF2.PdfFileReader(pdf_content)
import io

pdf_content = io.BytesIO(requests.get(buildurl(jornal, date, page)).content)
pdf_reader = PyPDF2.PdfFileReader(pdf_content)