1. 程式人生 > >【Python】實現網站備份檔案掃描+原始碼分析

【Python】實現網站備份檔案掃描+原始碼分析

一開始我用的requests庫的get方法

但是這種方法會自動下載檔案,所以不可取

後來發現urllib2的庫相對來說不錯

原始碼如下

# coding = utf-8
import urllib2
import socket
timeout=3
socket.setdefaulttimeout(timeout)

headers={'User-Agent':'Mozilla/5.0 (Windows NT 6.3; WOW64)AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102Safari/537.36'}

a = 'http://www.xxxxx.cn/1.rar'
try:
    req = urllib2.Request(url=a,headers=headers)
    response = urllib2.urlopen(req)
    print response.code   #返回狀態嗎 確定是不是存在
    print response.headers
    meta = response.info()
    file_size = int(meta.getheaders("Content-Length")[0])   #分析這個檔案的大小
    print file_size
except urllib2.URLError, e: 
         print e.reason