【发布时间】:2014-01-10 20:14:43
【问题描述】:
我从How to download a file using python in a 'smarter' way?得到这个代码?
但它会抛出一个错误:
in download
r.close()
UnboundLocalError: local variable 'r' referenced before assignment
我还想添加一个条件,即要下载的文件只能是 pdf。
import urllib2
import shutil
import urlparse
import os
def download(url, fileName=None):
def getFileName(url,openUrl):
if 'Content-Disposition' in openUrl.info():
# If the response has Content-Disposition, try to get filename from it
cd = dict(map(lambda x: x.strip().split('=') if '=' in x else (x.strip(),''),openUrl.info()['Content-Disposition'].split(';')))
if 'filename' in cd:
filename = cd['filename'].strip("\"'")
if filename: return filename
# if no filename was found above, parse it out of the final URL.
return os.path.basename(urlparse.urlsplit(openUrl.url)[2])
req = urllib2.Request(url)
try:
r = urllib2.urlopen(req)
except urllib2.HTTPError, e:
print e.fp.read()
try:
fileName = fileName or getFileName(url,r)
with open(fileName, 'wb') as f:
shutil.copyfileobj(r,f)
finally:
r.close()
download('http://www.altria.com/Documents/Altria_10Q_Filed10242013.pdf#?page=24')
这完全适用于 url:http://www.gao.gov/new.items/d04641.pdf 所以我的问题是为什么它不适用于某些 url,但对上面提到的 url 完全有效。
【问题讨论】:
-
您已经描述了您的问题,并且包含了一个示例程序。那挺好的。您仍然缺少 SO 帖子的关键要素:一个问题。 SO 是一个问答网站。像你这样的读者提出问题,而其他读者试图回答这些问题。你有什么问题?
标签: python