0.采用requests庫
雖然urllib庫應(yīng)用也很廣泛些楣,而且作為Python自帶的庫無需安裝,但是大部分的現(xiàn)在python爬蟲都應(yīng)用requests庫來處理復(fù)雜的http請求泊脐。requests庫語法上簡潔明了碘饼,使用上簡單易懂恩尾,而且正逐步成為大多數(shù)網(wǎng)絡(luò)爬取的標(biāo)準(zhǔn)弛说。
1. requests庫的安裝
采用pip安裝方式,在cmd界面輸入:
pip install requests
requests 官方文檔http://python-requests.org翰意。
2. 示例代碼
我們將處理http請求的頭部處理來簡單進(jìn)行反反爬蟲處理木人,以及代理的參數(shù)設(shè)置,異常處理等冀偶。
import requests
def download(url, num_retries=2, user_agent='wswp', proxies=None):
'''下載一個指定的URL并返回網(wǎng)頁內(nèi)容
參數(shù):
url(str): URL
關(guān)鍵字參數(shù):
user_agent(str):用戶代理(默認(rèn)值:wswp)
proxies(dict): 代理(字典): 鍵:‘http’'https'
值:字符串(‘http(s)://IP’)
num_retries(int):如果有5xx錯誤就重試(默認(rèn):2)
#5xx服務(wù)器錯誤醒第,表示服務(wù)器無法完成明顯有效的請求。
#https://zh.wikipedia.org/wiki/HTTP%E7%8A%B6%E6%80%81%E7%A0%81
'''
print('==========================================')
print('Downloading:', url)
headers = {'User-Agent': user_agent} #頭部設(shè)置进鸠,默認(rèn)頭部有時候會被網(wǎng)頁反扒而出錯
try:
resp = requests.get(url, headers=headers, proxies=proxies) #簡單粗暴稠曼,.get(url)
html = resp.text #獲取網(wǎng)頁內(nèi)容,字符串形式
if resp.status_code >= 400: #異常處理客年,4xx客戶端錯誤 返回None
print('Download error:', resp.text)
html = None
if num_retries and 500 <= resp.status_code < 600:
# 5類錯誤
return download(url, num_retries - 1)#如果有服務(wù)器錯誤就重試兩次
except requests.exceptions.RequestException as e: #其他錯誤霞幅,正常報錯
print('Download error:', e)
html = None
return html #返回html
print(download('http://www.baidu.com'))
結(jié)果:
Downloading: http://www.baidu.com
<!DOCTYPE html>
<!--STATUS OK-->
...
</script>
<script>
if(navigator.cookieEnabled){
document.cookie="NOJS=;expires=Sat, 01 Jan 2000 00:00:00 GMT";
}
</script>
</body>
</html>