python爬虫:读取PDF
Posted 小星星学数据
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python爬虫:读取PDF相关的知识,希望对你有一定的参考价值。
下面的代码可以实现用python读取PDF,包括读取本地和网络上的PDF。
pdfminer下载地址:https://pypi.python.org/packages/source/p/pdfminer/pdfminer-20140328.tar.gz
#!/usr/bin/python
# -*- encoding:utf-8 -*-
from urllib2 import urlopen
from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter
from pdfminer.converter import TextConverter
from pdfminer.layout import LAParams
from pdfminer.pdfpage import PDFPage
from cStringIO import StringIO
def convert_pdf_to_txt(fp):
rsrcmgr = PDFResourceManager()
retstr = StringIO()
codec = ‘utf-8‘
laparams = LAParams()
device = TextConverter(rsrcmgr, retstr, codec=codec, laparams=laparams)
interpreter = PDFPageInterpreter(rsrcmgr, device)
password = ""
maxpages = 0
caching = True
pagenos=set()
for page in PDFPage.get_pages(fp, pagenos, maxpages=maxpages, password=password,caching=caching, check_extractable=True):
interpreter.process_page(page)
fp.close()
device.close()
textstr = retstr.getvalue()
retstr.close()
return textstr
url=‘http://pythonscraping.com/pages/warandpeace/chapter1.pdf‘
fp = StringIO(urlopen(url).read()) # for url
# path=‘chapter1.pdf‘
# fp = file(path, ‘rb‘) # for path
text=convert_pdf_to_txt(fp)
print text
以上是关于python爬虫:读取PDF的主要内容,如果未能解决你的问题,请参考以下文章
分享《精通Python爬虫框架Scrapy》中文PDF+英文PDF+源代码
分享《精通Python爬虫框架Scrapy》中文PDF+英文PDF+源代码