2016-07-30 15 views
1

私はWebページからPDFを取得し、解析し、結果をPyPDF2を使用して画面に表示しようとしていました。私はそれが次のコードで問題なく動作ました:ちょうどので、私はそれはしかし、無駄な響き読むことができるファイルの書き込みPython 3の解析WebからのPDF

with open("foo.pdf", "wb") as f: 
    f.write(requests.get(buildurl(jornal, date, page)).content) 
pdfFileObj = open('foo.pdf', "rb") 
pdf_reader = PyPDF2.PdfFileReader(pdfFileObj) 
page_obj = pdf_reader.getPage(0) 
print(page_obj.extractText()) 

ので、私は、私はちょうどこれで仲介をカットしたい考え出し:

pdf_reader = PyPDF2.PdfFileReader(requests.get(buildurl(jornal, date, page)).content) 
page_obj = pdf_reader.getPage(0) 
print(page_obj.extractText()) 

しかし、これは私にAttributeError: 'bytes' object has no attribute 'seek'をもたらします。 requestsのPDFをPyPDF2に直接フィードするにはどうすればよいですか?偽へ

答えて

4

返されたcontentをを使用してファイル形式のオブジェクトに変換する必要があります:

import io 

pdf_content = io.BytesIO(requests.get(buildurl(jornal, date, page)).content) 
pdf_reader = PyPDF2.PdfFileReader(pdf_content) 
2

利用IOファイルの使用(Pythonの3):

import io 

output = io.BytesIO() 
output.write(requests.get(buildurl(jornal, date, page)).content) 
output.seek(0) 
pdf_reader = PyPDF2.PdfFileReader(output) 

は、私はあなたのコンテキストでテストしていないが、私はこの単純な例をテストし、それが働いた:

import io 

output = io.BytesIO() 
output.write(bytes("hello world","ascii")) 
output.seek(0) 
print(output.read()) 

収量を:

+0

申し訳ありませんが、忘れてしまったのは、Python3と互換性があることです –