如何使用Scrapy在线解析PDF页面?
How to use Scrapy to parse PDF pages online?
我尝试使用带有 PyPDF2 库的 Scrapy 在线抓取 PDF,但未成功。到目前为止,我能够导航所有链接并能够获取 PDF 文件,但通过 PyPDF2 提供它们似乎是一个问题。
注意:我的目标不是grab/save 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))
希望对您有所帮助。
我尝试使用带有 PyPDF2 库的 Scrapy 在线抓取 PDF,但未成功。到目前为止,我能够导航所有链接并能够获取 PDF 文件,但通过 PyPDF2 提供它们似乎是一个问题。
注意:我的目标不是grab/save 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))
希望对您有所帮助。