標籤:like hash urllib odi 連結 headers pytho safari 擷取
實現每個連結都能獨立緩衝,如果存在直接讀取,如果不存在,則擷取網頁,然後系列化後儲存到本地
目錄功能比較簡單:後續可能會改進
#!/usr/bin/env python#coding:utf-8#Created by Andy @ 2017/6/28import osimport hashlibimport urllib.requestimport randomimport timeimport gzipimport pickle# 簡單的反防爬,每次隨機選下headerheaders = [{‘User-Agent‘: ‘Mozilla/5.0 (Windows NT 6.3 WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Maxthon/4.4.8.1000 Chrome/30.0.1599.101 Safari/537.36‘}, {‘User-Agent‘: ‘Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:45.0) Gecko/20100101 Firefox/45.0‘}, {‘User-Agent‘: ‘Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 10.0; WOW64; Trident/7.0)‘}]def cache_html(url, header):# 根據不同連結產生不同的雜湊值,並以此為檔案名稱,保證一連結一快取檔案md = hashlib.md5()md.update(url.encode(encoding=‘utf8‘))file_name = md.hexdigest()# 判斷快取檔案是否已經存在,如果存在就直接讀取快取檔案path = os.path.join(base_path, file_name)if os.path.exists(path) and os.path.getsize(path):print("Cache file already exist!")with open(path, ‘rb‘) as read_f:html = pickle.load(read_f)try:html = gzip.decompress(html).decode(‘utf8‘) # 有些網站的資料經過壓縮了except:html = html.decode(‘utf8‘)else:req = urllib.request.Request(url, headers=header)html = urllib.request.urlopen(req).read()if not req or not html:print("Connection failed...")else:time.sleep(random.randint(1, 3))with open(file_name, ‘wb‘) as write_f:pickle.dump(html, write_f)try:html = gzip.decompress(html).decode(‘utf8‘)except:html = html.decode(‘utf-8‘)return htmlif __name__ == ‘__main__‘:header = random.choice(headers)base_path = os.path.dirname(os.path.abspath(__file__))url = ‘http://www.python.org‘html = cache_html(url, header)print(html)
緩衝網頁