如何以“更智能”的方式使用python下载文件?

时间:2009-05-14 08:21:43

标签: python http download

我需要通过Python中的http下载几个文件。

最明显的方法是使用urllib2:

import urllib2
u = urllib2.urlopen('http://server.com/file.html')
localFile = open('file.html', 'w')
localFile.write(u.read())
localFile.close()

但我必须以某种方式处理令人讨厌的网址,比如说:http://server.com/!Run.aspx/someoddtext/somemore?id=121&m=pdf。通过浏览器下载时,该文件具有可读的名称,即。 accounts.pdf

有没有办法在python中处理它,所以我不需要知道文件名并将它们硬编码到我的脚本中?

5 个答案:

答案 0 :(得分:41)

下载这样的脚本往往会推送一个标题告诉用户代理文件的名称:

Content-Disposition: attachment; filename="the filename.ext"

如果您可以抓住该标题,则可以获得正确的文件名。

another thread有一些代码可以提供Content-Disposition - 抓住。

remotefile = urllib2.urlopen('http://example.com/somefile.zip')
remotefile.info()['Content-Disposition']

答案 1 :(得分:35)

基于评论和@Oli的anwser,我提出了这样的解决方案:

from os.path import basename
from urlparse import urlsplit

def url2name(url):
    return basename(urlsplit(url)[2])

def download(url, localFileName = None):
    localName = url2name(url)
    req = urllib2.Request(url)
    r = urllib2.urlopen(req)
    if r.info().has_key('Content-Disposition'):
        # If the response has Content-Disposition, we take file name from it
        localName = r.info()['Content-Disposition'].split('filename=')[1]
        if localName[0] == '"' or localName[0] == "'":
            localName = localName[1:-1]
    elif r.url != url: 
        # if we were redirected, the real file name we take from the final URL
        localName = url2name(r.url)
    if localFileName: 
        # we can force to save the file as specified name
        localName = localFileName
    f = open(localName, 'wb')
    f.write(r.read())
    f.close()

从Content-Disposition获取文件名;如果它不存在,则使用URL中的文件名(如果重定向发生,则考虑最终的URL)。

答案 2 :(得分:23)

结合以上的大部分内容,这是一个更加pythonic的解决方案:

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])

    r = urllib2.urlopen(urllib2.Request(url))
    try:
        fileName = fileName or getFileName(url,r)
        with open(fileName, 'wb') as f:
            shutil.copyfileobj(r,f)
    finally:
        r.close()

答案 3 :(得分:1)

2 Kender

if localName[0] == '"' or localName[0] == "'":
    localName = localName[1:-1]

它不安全 - Web服务器可以将错误的格式化名称传递为[“file.ext]或[file.ext'],甚至是空的, localName [0] 将引发异常。 正确的代码可能如下所示:

localName = localName.replace('"', '').replace("'", "")
if localName == '':
    localName = SOME_DEFAULT_FILE_NAME

答案 4 :(得分:0)

使用$fi = new FilesystemIterator($appPath . '/vendor/username/repoName/tree/master/images', FilesystemIterator::SKIP_DOTS);

wget

使用urlretrieve:

custom_file_name = "/custom/path/custom_name.ext"
wget.download(url, custom_file_name)
如果不存在,

urlretrieve也会创建目录结构。