2016-09-30 107 views
0

我正在使用Scrapy蜘蛛,試圖使用slate從目錄中的多個PDF文件中提取文本。我沒有興趣將實際的PDF保存到磁盤,因此我建議查看https://docs.python.org/2/library/io.html#buffered-streams的io.bytesIO子類。創建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 

我越來越:

in_memory_pdf.read(response.body) 
TypeError: integer argument expected, got 'str' 

我怎樣才能得到這個工作?

回答

1

當你做in_memory_pdf.read(response.body)你應該通過讀取的字節數。你想初始化緩衝區,而不是讀入緩衝區。

在Python 2,只是初始化BytesIO爲:

in_memory_pdf = BytesIO(response.body) 

在Python 3,你不能因爲它預計字節使用BytesIO一個字符串。錯誤消息顯示response.body的類型爲str:我們必須對其進行編碼。

in_memory_pdf = BytesIO(bytes(response.body,'ascii')) 

但作爲一個PDF格式可以是二進制數據,我想這response.bodybytes,不str。在那種情況下,簡單的in_memory_pdf = BytesIO(response.body)工作。