How to download a file using python in a 'smarter' way?에서이 코드를 받았습니까?URL이 지정된 파일을 다운로드하고 콘텐츠 처리와 동일한 파일 이름을 저장하십시오.
하지만 오류가 발생합니다 :
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는 질의 응답 사이트입니다. 독자와 같은 독자는 질문을하고 다른 독자는 대답을 시도합니다. 귀하의 질문은 무엇인가? –