Python: urlretrieve 下载 PDF
我在用Python的urllib库里的urlretrieve()函数来从网站上下载一些PDF文件。可是,它(至少对我来说)突然不管用了,下载下来的数据都是损坏的(下载的文件只有15 KB,而应该是164 KB)。
我试过好几个PDF文件,结果都不行(比如这个random.pdf)。我就是搞不定这个问题,而我需要下载PDF文件来完成我正在做的项目。
下面是我用来下载PDF文件的代码示例(然后用pdftotext.exe来解析文本):
def get_html(url): # gets html of page from Internet
import os
import urllib2
import urllib
from subprocess import call
f_name = url.split('/')[-2] # get file name (url must end with '/')
try:
if f_name.split('.')[-1] == 'pdf': # file type
urllib.urlretrieve(url, os.getcwd() + '\\' + f_name)
call([os.getcwd() + '\\pdftotext.exe', os.getcwd() + '\\' + f_name]) # use xpdf to output .txt file
return open(os.getcwd() + '\\' + f_name.split('.')[0] + '.txt').read()
else:
return urllib2.urlopen(url).read()
except:
print 'bad link: ' + url
return ""
我还是个新手程序员,所以任何建议都非常欢迎!谢谢!
3 个回答
0
可能有点晚了,但你可以试试这个方法:把内容写入一个新文件,然后用textract来读取它。因为如果不这样做,我得到的文本里会有一些不想要的字符,比如‘#$’。
import requests
import textract
url = "The url which downloads the file"
response = requests.get(url)
with open('./document.pdf', 'wb') as fw:
fw.write(response.content)
text = textract.process("./document.pdf")
print('Result: ', text)
2
将文件写入磁盘:
myfile = open("out.pdf", "w")
myfile.write(req.content)
9
我建议你试试requests这个库。它是一个非常好用的库,可以让你在简单的接口背后,隐藏掉很多复杂的实现细节。
>>> import requests
>>> req = requests.get("http://www.mathworks.com/moler/random.pdf")
>>> len(req.content)
167633
>>> req.headers
{'content-length': '167633', 'accept-ranges': 'bytes', 'server': 'Apache/2.2.3 (Red Hat) mod_jk/1.2.31 PHP/5.3.13 Phusion_Passenger/3.0.9 mod_perl/2.0.4 Perl/v5.8.8', 'last-modified': 'Fri, 15 Feb 2008 17:11:12 GMT', 'connection': 'keep-alive', 'etag': '"30863b-28ed1-446357e3d4c00"', 'date': 'Sun, 03 Feb 2013 05:53:21 GMT', 'content-type': 'application/pdf'}
顺便说一下,你只下载到15kb的原因是你的网址写错了。正确的网址应该是
http://www.mathworks.com/moler/random.pdf
但是你现在请求的是
http://www.mathworks.com/moler/random.pdf/
>>> import requests
>>> c = requests.get("http://www.mathworks.com/moler/random.pdf/")
>>> len(c.content)
14390