2016-07-30 8 views
1

웹 페이지에서 PDF를 가져와 구문 분석하고 결과를 PyPDF2을 사용하여 화면에 인쇄하려고했습니다. 나는 다음과 같은 코드로 문제없이 작동 그것을 가지고 : 그냥 그렇게 그때는하지만 낭비 소리 읽을 수있는 파일을 작성Python 3 구문 분석 웹에서 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 파일의 사용 (파이썬 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()) 

수율을 :

b'hello world' 
+0

죄송합니다. 필자는 Python3 호환이 필요하다는 점을 잊어 버렸습니다. –