在Python中使用PDFMiner处理在线PDF文件。需要编码URL吗?
我想用 PDFMiner
从网上提取 PDF 文件的内容。
我的代码是基于 文档 中的示例,这个示例是用来提取硬盘上 PDF 文件内容的:
# Open a PDF file.
fp = open('mypdf.pdf', 'rb')
# Create a PDF parser object associated with the file object.
parser = PDFParser(fp)
# Create a PDF document object that stores the document structure.
document = PDFDocument(parser)
这个方法在稍微修改后效果不错。
现在,我尝试使用 urllib2.openurl
来处理在线 PDF 文件,但这并不奏效。我收到了一个错误信息:coercing to Unicode: need string or buffer, instance found
。
我该如何从 urllib2.openurl
获取一个字符串(或者其他什么),使得它和我用 open
函数打开 PDF 文件名时得到的结果一样(而不是 URL)呢?
如果我的问题不清楚,请告诉我。
1 个回答
4
好吧,我终于找到了解决办法,
我使用了 Request
和 StringIO
,把 open('my_file', 'rd')
这个命令给去掉了。
from urllib2 import Request
from StringIO import StringIO
url = 'my_url'
open = urllib2.urlopen(Request(url)).read()
memoryFile = StringIO(open)
parser = PDFParser(memoryFile)
这样一来,Python 就把网址当成一个文件来处理了。