Python爬蟲9-request包介紹及應用

GitHub代碼練習地址:1.兩種簡單get請求方法:https://github.com/Neo-ML/PythonPractice/blob/master/SpiderPrac13_requests1.py
           2.帶請求頭與參數的get請求:https://github.com/Neo-ML/PythonPractice/blob/master/SpiderPrac14_requests2.py


Requests-獻給人類

  
  是urllib模塊的完美替換,兩者功能基本相同
  HTTP for Humans,更簡潔更友好

  繼承了urllib的全部特徵
  底層使用的是urllib3
  開源地址: https://github.com/requests/requests
  中文文檔: http://docs.python-requests.org/zh_CN/latest/index.html
  安裝: conda install requests
 
1、兩種get請求方法:

  requests.get(url)
  requests.request("get", url)
  能夠帶有headers和parmas參數來請求

2、requests下使用proxy代理
       proxies = {
"http":"address of proxy",
"https": "address of proxy"
}

rsp = requests.request("get", "http:xxxxxx", proxies=proxies)
代理有可能報錯,若是使用人數多,考慮安全問題,可能會被強行關閉

用戶驗證
代理驗證
可能須要使用HTTP basic Auth, 能夠這樣
格式爲 用戶名:密碼@代理地址:端口地址
proxy = { "http": "china:123456@192.168.1.123:4444"}
rsp = requests.get("http://baidu.com", proxies=proxy)
web客戶端驗證
若是遇到web客戶端驗證,須要添加auth=(用戶名,密碼)
autu=("test1", "123456")#受權信息
rsp = requests.get("http://www.baidu.com", auth=auth)

3、requests下的cookie與session以及ssl證書相關問題
cookie
requests能夠自動處理cookie信息
rsp = requests.get("http://xxxxxxxxxxx")
若是對方服務器給傳送過來cookie信息,則能夠經過反饋的cookie屬性獲得
返回一個cookiejar實例
cookiejar = rsp.cookies

能夠講cookiejar轉換成字典
cookiedict = requests.utils.dict_from_cookiejar(cookiejar)

session
跟服務器端session不是一個東東
模擬一次會話,從客戶端瀏覽器連接服務器開始,到客戶端瀏覽器斷開
能讓咱們跨請求時保持某些參數,好比在同一個session實例發出的 全部請求之間保持cookie

建立session對象,能夠保持cookie值
ss = requests.session()

headers = {"User-Agetn":"xxxxxxxxxxxxxxxxxx"}

data = {"name":"xxxxxxxxxxx"}

此時,由建立的session管理請求,負責發出請求,
ss.post("http://www.baidu.com", data=data, headers=headers)

rsp = ss.get("xxxxxxxxxxxx")

https請求驗證ssl證書
參數verify負責表示是否須要驗證ssL證書,默認是True
若是不須要驗證ssl證書,則設置成False表示關閉

rsp = requests.get("https://www.baidu.com", verify=False)
若是用verify=True訪問某些證書有問題的網站會報錯。
相關文章
相關標籤/搜索