1. 程式人生 > >python爬蟲讀書筆記(1)

python爬蟲讀書筆記(1)

1.使用urllib2模組下載URL

import urllib2
def download(url):
    return urllib2.urlopen(url).read()

2.捕獲異常

出現下載錯誤時,該函式能夠捕獲異常,然後返回None。

import urllib2
def download(url):
    print 'Downloading:',url
    try:
        html=urllib2.urlopen(url).read()
    except urllib2.URLError as e:
        print 'Downloading error',e.reason
        html=None
    return html

3.重試下載

4xx錯誤發生在請求存在問題時,而5xx錯誤則發生在服務端存在問題時。 所以, 我們只需要確保download 函式在 發生5xx 錯誤時重試下載即可。下面是支援重試下載功能的新版本程式碼。
 

def  download(url,num_retries=2):
    print('Downloading',url)
    try:
        html=urllib.urlopen(url).read()
    except urllib2.URLError as e:
        print('Downloading 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

4.設定使用者代理

設定一個預設的使用者代理“wswp”

import urllib2
def download(url,user_agent='wswp',num_retries=2):
    print('Downloading:',url)
    headers={'User-agent':user_agent}
    request=urllib2.Request(url,headers=headers)
    try:
        html=urllib.urlopen(request).read()
    except urllib2.URLError as e:
        print('Downloading 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