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

时间:2018-09-26 10:28:58

标签: python scrapy pypdf2

我尝试将Scrapy与PyPDF2库一起使用,无法在线上对PDfs进行爬网。到目前为止,我已经能够导航所有链接并能够获取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'

我在做什么错了?

1 个答案:

答案 0 :(得分:2)

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

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

希望这会有所帮助。