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

Cod*_*key 2 python scrapy pypdf2

我尝试使用带有 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
Run Code Online (Sandbox Code Playgroud)

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

我究竟做错了什么?

Anu*_*har 7

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

# use this instead of passing response.body directly into PyPDF2
reader = PyPDF2.PdfFileReader(io.BytesIO(response.body))
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助。