【问题标题】:Python 3 parse PDF from webPython 3 从网络解析 PDF
【发布时间】:2026-02-22 03:25:01
【问题描述】:

我试图从网页中获取 PDF,对其进行解析并使用 PyPDF2 将结果打印到屏幕上。我使用以下代码使其正常工作:

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' object has no attribute 'seek'。如何将来自requests 的 PDF 直接输入到 PyPDF2?

【问题讨论】:

    标签: python pdf python-requests pypdf2


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

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

      import io
      
      output = io.BytesIO()
      output.write(requests.get(buildurl(jornal, date, page)).content)
      output.seek(0)
      pdf_reader = PyPDF2.PdfFileReader(output)
      

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

      import io
      
      output = io.BytesIO()
      output.write(bytes("hello world","ascii"))
      output.seek(0)
      print(output.read())
      

      产量:

      b'hello world'
      

      【讨论】: