gpt4 book ai didi

python - 如何使用Scrapy在线解析PDF页面?

转载 作者:行者123 更新时间:2023-12-01 22:04:43 29 4
gpt4 key购买 nike

我尝试使用带有 PyPDF2 库的 Scrapy 在线抓取 PDF,但未成功。到目前为止,我能够导航所有链接并能够获取 PDF 文件,但通过 PyPDF2 提供它们似乎是一个问题。

注意:我的目标不是抓取/保存 PDF 文件,我打算通过首先将 PDF 转换为文本然后使用其他方法处理该文本来解析它们。

为简洁起见,我没有在此处包含整个代码。这是我的部分代码:

import io
import re
import PyPDF2
import scrapy
from scrapy.item import Item

class ArticleSpider(scrapy.Spider):
name = "spyder_ARTICLE"
start_urls = ['https://legion-216909.appspot.com/content.htm']

def parse(self, response):
for article_url in response.xpath('//div//a/@href').extract():
yield response.follow(article_url, callback=self.parse_pdf)

def parse_pdf(self, response):
""" Peek inside PDF to check for targets.
@return: PDF content as searcable plain-text string
"""
reader = PyPDF2.PdfFileReader(response.body)
text = u""

# Title is optional, may be None
if reader.getDocumentInfo().title: text += reader.getDocumentInfo().title
# XXX: Does handle unicode properly?
for page in reader.pages: text += page.extractText()

return text

每次我运行代码时,蜘蛛都会尝试 reader = PyPDF2.PdfFileReader(response.body) 并给出以下错误:AttributeError: 'bytes' object has no attribute 'seek '

我做错了什么?

最佳答案

这似乎不是scrapy的问题。 PyPDF2 需要二进制数据流。

# use this instead of passing response.body directly into PyPDF2
reader = PyPDF2.PdfFileReader(io.BytesIO(response.body))

希望这对您有所帮助。

关于python - 如何使用Scrapy在线解析PDF页面?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52515592/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com