緩衝網頁

來源:互聯網
上載者:User

標籤: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)

 

緩衝網頁

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.