2017-06-11 57 views
0

我想從pdf中遠程提取文本。使用urllib2遠程讀取pdf

網址是這個http://loc.gov/aba/publications/FreeLCC/A-text.pdf

我的代碼如下

import urllib2 
import PyPDF2 
import io 

URL = 'http://loc.gov/aba/publications/FreeLCC/A-outline.pdf' 
remote_file = urllib2.urlopen(URL).read() 
memory_file = io.BytesIO(remote_file) 

read_pdf = PyPDF2.PdfFileReader(memory_file) 
number_of_pages = read_pdf.getNumPages() 

for i in range(0, number_of_pages): 
    pageObj = read_pdf.getPage(i) 
    page = pageObj.extractText() 
    print (page) 

我得到一個403 HTTP錯誤。我究竟做錯了什麼?

回答

2

Source

import urllib2 
import PyPDF2 
import io 

URL = 'http://loc.gov/aba/publications/FreeLCC/A-outline.pdf' 
req = urllib2.Request(URL, headers={'User-Agent' : "Magic Browser"}) 
remote_file = urllib2.urlopen(req).read() 
memory_file = io.BytesIO(remote_file) 

read_pdf = PyPDF2.PdfFileReader(memory_file) 
number_of_pages = read_pdf.getNumPages() 

for i in range(0, number_of_pages): 
    pageObj = read_pdf.getPage(i) 
    page = pageObj.extractText() 
    print (page)