我在一个抓取蜘蛛上工作,试图提取一个目录中的文本多个pdf,使用slate (https://pypi.python.org/pypi/slate)。我没有兴趣将实际的PDF保存到磁盘上,因此有人建议我研究一下https://docs.python.org/2/library/io.html#buffered-streams上的io.bytesIO子类。基于Creating bytesIO object,我已经用pdf初始化了bytesIO类,但现在我需要将数据传递给slate模块。到目前为止,我有:
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)
发布于 2016-10-01 04:24:05
你已经知道答案了。Python TypeError消息中清楚地提到了这一点,文档中也明确了这一点:
class io.BytesIO([initial_bytes])
BytesIO接受字节。并且您正在传递它的内容。即: response.body,它是一个字符串。
https://stackoverflow.com/questions/39799427
复制相似问题