我在Python中使用urllib的urlretrieve()函数,以便尝试从网站获取一些pdf。它已经(至少对我而言)停止工作,正在下载损坏的数据(15KB而不是164KB)。
我已经测试了几个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 ""我是一个新手程序员,所以任何输入都会很棒!谢谢
发布于 2013-02-03 13:54:32
我建议你试试requests。这是一个非常好的库,它将所有的实现隐藏在一个简单的api后面。
>>> 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的下载是因为你的url是错误的。它应该是
http://www.mathworks.com/moler/random.pdf但你是GETing
http://www.mathworks.com/moler/random.pdf/
>>> import requests
>>> c = requests.get("http://www.mathworks.com/moler/random.pdf/")
>>> len(c.content)
14390发布于 2015-06-28 03:08:46
要将文件写入光盘,请执行以下操作:
myfile = open("out.pdf", "w")
myfile.write(req.content)发布于 2017-05-30 18:21:19
也许有点晚了,但你可以试试这个:只需将内容写到一个新文件中,并使用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)https://stackoverflow.com/questions/14669827
复制相似问题