在mooc上學習嵩天老師的爬蟲課,整理一些學習筆記~
Requests庫的安裝
Requests庫的安裝
Win平臺: “以管理員身份運行”cmd,執行pip install requests
這裏我要說明的一點是:在我的電腦裏同時安裝了python2和python3,執行上述語句在python3中會報錯,解決方案是執行
pip3 install requests
可以運行如下程序測試Requests庫是否成功安裝
>>> import requests
>>> r=requests.get("http://www.baidu.com")
>>> print(r.status_code)
200
>>> r.text
u'<!DOCTYPE html>\r\n<!--STATUS OK--><html> <head><meta http-equiv=content-type content=text/html;charset=utf-8><meta http-equiv=X-UA-Compatible content=IE=Edge><meta content=always name=referrer><link rel=stylesheet type=text/css href=http://s1.bdstatic.com/r/www/cache/bdorz/baidu.min.css><title>\xe7\x99\xbe\xe5\xba\xa6\xe4\xb8\x80\xe4\xb8\x8b\xef\xbc\x8c\xe4\xbd\xa0\xe5\xb0\xb1\xe7\x9f\xa5\xe9\x81\x93</title></head> <body link=#0000cc> <div id=wrapper> <div id=head> <div class=head_wrapper> <div class=s_form> <div class=s_form_wrapper> <div id=lg> <img hidefocus=true src=//www.baidu.com/img/bd_logo1.png width=270 height=129> </div> <form id=form name=f action=//www.baidu.com/s class=fm> <input type=hidden name=bdorz_come value=1> <input type=hidden name=ie value=utf-8> <input type=hidden
r.status_code爲200表示成功
Requests庫的7個主要方法
- requests.request() 構造一個請求,支撐以下各方法的基礎方法
- requests.get() 獲取HTML網頁的主要方法,對應於HTTP的GET
- requests.head() 獲取HTML網頁頭信息的方法,對應於HTTP的HEAD
- requests.post() 向HTML網頁提交POST請求的方法,對應於HTTP的POST
- requests.put() 向HTML網頁提交PUT請求的方法,對應於HTTP的PUT
- requests.patch() 向HTML網頁提交局部修改請求,對應於HTTP的PATCH
- requests.delete() 向HTML頁面提交刪除請求,對應於HTTP的DELETE
Requests庫的get()方法
requests.get()
- url : 擬獲取頁面的url鏈接
- params : url中的額外參數,字典或字節流格式,可選
- **kwargs: 12個控制訪問的參數
Response對象
Response對象包含服務器返回的所有信息,也包含請求的Request信息
Response對象的屬性
- r.status_code HTTP請求的返回狀態,200表示連接成功,404表示失敗
- r.text HTTP響應內容的字符串形式,即,url對應的頁面內容
- r.encoding 從HTTP header中猜測的響應內容編碼方式
- r.apparent_encoding 從內容中分析出的響應內容編碼方式(備選編碼方式)
- r.content HTTP響應內容的二進制形式
一般會有如下的處理流程
理解Response的編碼
- r.encoding 從HTTP header中猜測的響應內容編碼方式
- r.apparent_encoding 從內容中分析出的響應內容編碼方式(備選編碼方式)
r.encoding:如果header中不存在charset,則認爲編碼爲ISO‐8859‐1
r.text根據r.encoding顯示網頁內容
r.apparent_encoding:根據網頁內容分析出的編碼方式
可以看作是r.encoding的備選
爬取網頁的通用代碼框架
理解Requests庫的異常
- requests.ConnectionError 網絡連接錯誤異常,如DNS查詢失敗、拒絕連接等
- requests.HTTPError HTTP錯誤異常
- requests.URLRequired URL缺失異常
- requests.TooManyRedirects 超過最大重定向次數,產生重定向異常
- requests.ConnectTimeout 連接遠程服務器超時異常
- requests.Timeout 請求URL超時,產生超時異常
r.raise_for_status()方法
- r.raise_for_status() 如果不是200,產生異常requests.HTTPError
增加額外的if語句,該語句便於利用try‐except進行異常處理
爬取網頁的通用代碼框架
下面是演示例子
HTTP協議及Requests庫方法
HTTP協議
HTTP,Hypertext Transfer Protocol,超文本傳輸協議。HTTP是一個基於“請求與響應”模式的、無狀態的應用層協議
HTTP協議採用URL作爲定位網絡資源的標識,URL格式如下:
port: 端口號,缺省端口爲80
path: 請求資源的路徑
HTTP URL實例:
http://www.bit.edu.cn
http://220.181.111.188/duty
HTTP URL的理解:
URL是通過HTTP協議存取資源的Internet路徑,一個URL對應一個數據資源
HTTP協議對資源的操作
通過URL和命令管理資源,操作獨立無狀態,網絡通道及服務器成爲了黑盒子
理解PATCH和PUT的區別
假設URL位置有一組數據UserInfo,包括UserID、UserName等20個字段
需求:用戶修改了UserName,其他不變
- 採用PATCH,僅向URL提交UserName的局部更新請求
- 採用PUT,必須將所有20個字段一併提交到URL,未提交字段被刪除
HTTP協議與Requests庫
HTTP協議方法 Requests庫方法 功能一致性
- GET requests.get() 一致
- HEAD requests.head() 一致
- POST requests.post() 一致
- PUT requests.put() 一致
- PATCH requests.patch() 一致
- DELETE requests.delete() 一致
Requests 庫的head()方法
>>> r = requests.head('http://httpbin.org/get')
>>> r.headers
{'Content‐Length': '238', 'Access‐Control‐Allow‐Origin': '*', 'Access‐
Control‐Allow‐Credentials': 'true', 'Content‐Type':
'application/json', 'Server': 'nginx', 'Connection': 'keep‐alive',
'Date': 'Sat, 18 Feb 2017 12:07:44 GMT'}
>>> r.text
''
Requests庫的post()方法
>>> payload = {'key1': 'value1', 'key2': 'value2'}
>>> r = requests.post('http://httpbin.org/post', data = payload)
>>> print(r.text)
{ ...
"form": {
"key2": "value2",
"key1": "value1"
},
}
以及>>> r = requests.post('http://httpbin.org/post', data = 'ABC')
>>> print(r.text)
{ ...
"data": "ABC"
"form": {},
}
Requests庫的put()方法
>>> payload = {'key1': 'value1', 'key2': 'value2'}
>>> r = requests.put('http://httpbin.org/put', data = payload)
>>> print(r.text)
{ ...
"form": {
"key2": "value2",
"key1": "value1"
},
}