我正在使用slate(https://pypi.python.org/pypi/slate)试图在目录中提取多个pdf文本的scrapy蜘蛛。我没有兴趣将实际的PDF保存到磁盘,因此我建议查看https://docs.python.org/2/library/io.html#buffered-streams的io.bytesIO子类。基于Creating bytesIO object,我已经初始化了pdf体的bytesIO类,但现在我需要将数据传递给slate模块。到目前为止,我有:创建后访问bytesIO对象
def save_pdf(self, response):
in_memory_pdf = BytesIO(response.body)
with open(in_memory_pdf, 'rb') as f:
doc = slate.PDF(f)
print(doc[0])
我越来越:
in_memory_pdf.read(response.body)
TypeError: integer argument expected, got 'str'
我怎样才能得到这个工作?
编辑:
with open(in_memory_pdf, 'rb') as f:
TypeError: coercing to Unicode: need string or buffer, _io.BytesIO found
编辑2:
def save_pdf(self, response):
in_memory_pdf = BytesIO(bytes(response.body))
in_memory_pdf.seek(0)
doc = slate.PDF(in_memory_pdf)
print(doc)
尝试'in_memory_pdf = BytesIO(bytes(response.body))'。 – martineau
谢谢,这解决了最初的问题! – user61629
尝试使用['StringIO'](https://docs.python.org/2/library/stringio.html#module-StringIO)而不是'BytesIO'。还要注意的是,对于任何一个,您都不需要'with open(...)as f',只需在使用'in_memory_pdf.seek(0)'创建后将其倒回到开头,然后使用'in_memory_pdf'_instead_ of' F'。 – martineau