gpt4 book ai didi

Python:urlretrieve PDF 下载

转载 作者:太空宇宙 更新时间:2023-11-03 12:33:53 26 4
gpt4 key购买 nike

我在 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 ""

我是一名新手程序员,所以任何输入都会很棒!谢谢

最佳答案

我建议尝试 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 的文件是因为您的网址错误。应该是

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

关于Python:urlretrieve PDF 下载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14669827/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com