1.我們?yōu)槭裁粗攸c(diǎn)學(xué)習(xí)使用requests模塊,而不是urllib
1.requests的底層實(shí)現(xiàn)就是urllib
2.requests在python2 和 python3 中通用,方法完全一樣
3.requests 簡(jiǎn)單易用
4.requests 能夠自動(dòng)幫助我們解壓(gizp壓縮的等)網(wǎng)頁(yè)內(nèi)容
2.requests 的作用
發(fā)送網(wǎng)絡(luò)請(qǐng)求,返回響應(yīng)數(shù)據(jù)
3.requests 模塊發(fā)送簡(jiǎn)單的請(qǐng)求,獲取響應(yīng)
需求:通過(guò)requests 向百度首頁(yè)發(fā)送請(qǐng)求,獲取百度首頁(yè)的數(shù)據(jù);
response = request.get(url)
response 的常用屬性
- response.text
- response.stantus_code
- response.request.headers
- response.headers
3.1 response.text 和 response.content 的區(qū)別
response.text
- 類型:str
- 解碼類型: 根據(jù)HTTP 頭部對(duì)響應(yīng)的編碼作出有根據(jù)的推測(cè),推測(cè)的文本編碼
- 如何修改編碼方式:response.encoding=”gbk”
response.content
- 類型:bytes
- 解碼類型: 沒(méi)有指定
- 如何修改編碼方式:response.content.deocde(“utf8”)
獲取網(wǎng)頁(yè)源碼的通用方式:
response.content.decode()
response.content.decode("GBK")
response.text
4.發(fā)送帶header的請(qǐng)求
帶上 headers 的作用:
模擬瀏覽器,欺騙服務(wù)器,獲取和瀏覽器一致的內(nèi)容
header的形式:字典
headers ={"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36"}
用法
requests.get(url,headers=headers)
5.發(fā)送帶參數(shù)的請(qǐng)求
例如:https://www.baidu.com/s?wd=python&c=b
參數(shù)的形式:字典
kw = {'wd':'橘子'}
用法
requests.get(url,params=kw)
注意點(diǎn)
在url地址中,很多參數(shù)是沒(méi)有用的,比如百度搜索的url地址,其中參數(shù)只有一個(gè)字段有用,其他的都可以刪除
對(duì)應(yīng)的,在后續(xù)的爬蟲(chóng)中,越到很多參數(shù)的url地址,都可以嘗試刪除參數(shù)