Requests庫從入門到放棄
一個很牛逼的http庫,就這樣子
1.get,post,cookie,header是什么還說么钮热?直接上代碼
2.安裝requests庫
pip install requests
3.get方法使用
import requests
r = requests.get('https://github.com/timeline.json')
print r.text
4.post方法使用
(1)普通post請求發(fā)送數(shù)據(jù)
import requests
#傳遞的數(shù)據(jù)用字典表示
payload = {'username':'xiaoming','password':'123456'}
r = requests.post('https://github.com/timeline.json',data=payload)
print r.text
(2)post請求發(fā)送文件(文件上傳)
url = 'http://httpbin.org/post'
files = {'file': open('report.xls', 'rb')}
r = requests.post(url, files=files)
print r.text
5.返回值的說明
r.text
#Requests 會使用基于 HTTP 頭部對響應(yīng)的編碼作出有根據(jù)的推測校辩,就是編碼好的文本內(nèi)容
r.content
#Requests的返回二進制內(nèi)容
r.json
#Requests的內(nèi)置json解析器窘问,如果返回的是json內(nèi)容
6.定制請求頭
為請求添加頭部,給headers參數(shù)傳遞進去一個字典就好了
url = 'https://api.github.com/some/endpoint'
headers = {'user-agent': 'my-app/0.0.1'}
r = requests.get(url, headers=headers)
print r.text
7.返回狀態(tài)碼的說明
r = requests.get('http://httpbin.org/get')
print r.status_code
8.帶cookie的請求
url = 'http://httpbin.org/cookies'
#working就是實際通過瀏覽器抓到的一大坨的cookie的東西宜咒,cookies_are是固定格式惠赫,必須寫
cookies = dict(cookies_are='working')
r = requests.get(url, cookies=cookies)
print r.text
#獲取響應(yīng)中的cookie
url = 'http://example.com/some/cookie/setting/url'
r = requests.get(url)
print r.cookies['example_cookie_name']
9.超時(不管什么網(wǎng)絡(luò)庫都有超時對不對)
#timeout=5
#在經(jīng)過以 timeout參數(shù)設(shè)定的秒數(shù)時間之后停止等待響應(yīng),拋異常
requests.get('http://github.com', timeout=5)