天天看點

python 爬蟲-1:下載下傳網頁源代碼

下載下傳靜态網頁源代碼的 python 爬蟲函數源代碼:

import urllib2
def download(url, num_retries = 5):
    '''
    function: 下載下傳網頁源代碼,如果遇到 5xx 錯誤狀态,則繼續嘗試下載下傳,直到下載下傳 num_retries 次為止。
    '''
    print "downloading " , url
    try:
        html = urllib2.urlopen(url).read()
    except urllib2.URLError as e:
        print "download error: " , e.reason
        html = None
        if num_retries > 0:
            if hasattr(e,'code') and 500 <= e.code < 600:
                return download(url, num_retries-1)

    return html           

其中 url 即為你想現在的網頁位址。 num_reties 為遇到 5xx 錯誤的時候,重試下載下傳的次數。

具體詳見我的部落格:

www.wangs0622.com