创建 bytesIO 对象

use*_*629 6 python pdf

我正在研究Scrapy蜘蛛,尝试使用slate从目录中的多个 PDF 文件中提取文本。我对将实际的 PDF 保存到磁盘没有兴趣,因此建议我查看https://docs.python.org/2/library/io.html#buffered-streams上的 io.bytesIO 子类。

但是我不确定如何将 PDF 正文传递给 bytesIO 类,然后传递虚拟 PDF 板岩来获取文本。到目前为止我有:

class Ove_Spider(BaseSpider):

    name = "ove"


    allowed_domains = ['myurl.com']
    start_urls = ['myurl/hgh/']


    def parse(self, response):
        for a in response.xpath('//a[@href]/@href'):
            link = a.extract()
            if link.endswith('.pdf'):
                link = urlparse.urljoin(base_url, link)
                yield Request(link, callback=self.save_pdf)

    def save_pdf(self, response):

      in_memory_pdf = BytesIO()
      in_memory_pdf.read(response.body) # Trying to read in PDF which is in response body
Run Code Online (Sandbox Code Playgroud)

我越来越:

in_memory_pdf.read(response.body)
TypeError: integer argument expected, got 'str'
Run Code Online (Sandbox Code Playgroud)

我怎样才能让它发挥作用?

Jea*_*bre 11

当你这样做时,in_memory_pdf.read(response.body)你应该传递要读取的字节数。您想要初始化缓冲区,而不是读入其中。

在 python 2 中,只需初始化BytesIO为:

 in_memory_pdf = BytesIO(response.body)
Run Code Online (Sandbox Code Playgroud)

在 Python 3 中,您不能使用BytesIO字符串,因为它需要字节。错误消息显示其response.body类型为str:我们必须对其进行编码。

 in_memory_pdf = BytesIO(bytes(response.body,'ascii'))
Run Code Online (Sandbox Code Playgroud)

但由于 pdf 可以是二进制数据,我想那response.body将是bytes,而不是str。在这种情况下,简单的in_memory_pdf = BytesIO(response.body)方法就可以了。