中文文檔 API:?http://docs.python-requests.org/zh_CN/latest/index.html
1.使用requests發(fā)送請(qǐng)求
????response = requests.get(url)
????response的常用方法:
? ? ? ? response.text:requests模塊根據(jù)響應(yīng)頭對(duì)返回的數(shù)據(jù)進(jìn)行解密(可能會(huì)解碼錯(cuò)誤)务甥,可以用response.encoding="utf-8"進(jìn)行修改
? ? ? ? response.content:返回響應(yīng)內(nèi)容的bytes數(shù)據(jù),使用decode()解碼
? ? ? ? response.status_code:響應(yīng)的狀態(tài)碼
? ? ? ? response.request.headers:請(qǐng)求的headers信息
? ? ? ? response.headers:響應(yīng)的頭部信息
2.發(fā)送帶有header的請(qǐng)求
? ??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)
3.發(fā)送帶參數(shù)的請(qǐng)求????
? ? params={"key":"value"}
? ? requests.get(url, params=params)
4.發(fā)送post請(qǐng)求
? ? data={}
? ? headers={}
? ? requests.post(url, data=data, headers= headers)
5.使用代理
代理的作用:1)防止服務(wù)器識(shí)別為同一個(gè)ip訪問
? ? ? ? ? ? ? ? ? ? ? 2)防止個(gè)人信息泄露
proxies={
? ? ? ? "http":"http://...",
? ? ? ? "https":"htttps://..."
}
requests.get(url, proxies=proxies)
6.使用session發(fā)送請(qǐng)求
? ? session = requests.session()
? ? responce = session.get(url)
? ? session可以記住服務(wù)器返回的cookie,能夠?qū)崿F(xiàn)會(huì)話保持
7.requests技巧
????1)requests.utils.dict_from_cookiejar :將cookie對(duì)象轉(zhuǎn)化為字典
requests.utils.cookiejar_from_dict: 反之
?????2)取消SSL證書驗(yàn)證
response = requests.get(url, verify=False)
????3)設(shè)置超時(shí)時(shí)間
response = requests.get(url, timeout=10)
????4)判斷請(qǐng)求是否成功
assert response.status_code == 200
????5)url地址解碼
requests.utils.unquote()