1. 程式人生 > >python 獲取請求連結下載檔案的大小和檔案特徵

python 獲取請求連結下載檔案的大小和檔案特徵

###根據url連結提取下載檔案的大小特徵和下載檔案型別
def getRemoteFileSize(url, proxy=None):
    '''
    通過content-length頭獲取遠端檔案大小
    '''
    opener = urllib2.build_opener()
    if proxy:
        if url.lower().startswith('https://'):
            opener.add_handler(urllib2.ProxyHandler({'https' : proxy}))
        elif url.lower().startswith('http://'):
            opener.add_handler(urllib2.ProxyHandler({'http' : proxy}))
        else:
            opener.add_handler(urllib2.ProxyHandler({'ftp': proxy}))
    try:
        request = urllib2.Request(url)
        request.get_method = lambda: 'HEAD'
        response = opener.open(request)
        response.read()
    except Exception, e:
        # 遠端檔案不存在
        return 0, 0
    else:
        getfileSize = dict(response.headers).get('content-length', 0)
        filesize = round(float(getfileSize) / 1048576, 2)
        getContentType = dict(response.headers).get('content-type', 0)
        return filesize, getContentType