介紹
python request模塊通過模擬用戶訪問web網站,通過post,get的方法實現網站互動
安裝
pip 安裝
pip install requests
或源碼
git clone git://github.com/kennethreitz/request.git
用法
導入模塊
>>>import requests
get獲取網頁信息,保存名為r的Response
>>>r = request.get('https://github.com/timeline.json')
request 請求類型
>>>r = request.post('https://httpbin.org/post')
>>>r = request.put('http://httpbin.org/put')
>>>r = request.delete('http://httpbin.org/delete')
>>>r = request.head('http://httbin.org/head')
>>>r = request.options('http://httpbin.org/options')
request url傳遞參數
requsets 允許使用params關鍵字參數,並且以一個字典的形式來提供這些參數,如你想傳遞key1=value1和key2=value2 到httpbin.org/get,你可以使用以下代碼:
>>> payload = {'key1':'value1','key2':'value2'}
>>> r = requests.get("http://httbin.org/head",params=payload)
>>>print(r.url)
注意:字典值為None的鍵都不會被添加到url的參數字符串里
還可以將一個列表作為值傳入
>>>payload = {'key1','value1','key2':['value2','value3']}
>>>r = request.get('http://httpbin.org/get',params=payload)
>>>print(r.url)
request 響應內容
>>>import requests
>>>r.request.get('https://github.com/timeline.json')
>>>r.text # 返回請求的內容
>>>r.encoding # 返回編碼、
>>>r.encoding='ISO-8859-1' # 設置編碼
設置了新的編碼后,再次訪問r.text,Request都將會使用r.encoding設置新的編碼
用途:html 或者xm自身可以指定編碼,使用r.content找到對應的編碼,然后設置使r.encoding為相應的編碼,這樣就能使用正確的編碼解析r.text了
二進制響應內容
>>>r.content
>>>from PIL import Image
>>>from io import BytesIO
>>i = Image.open(BytesIO(r.content))
用途:把請求的二進制數據創建一張圖片,可以使用此段代碼
JSON 響應內容
>>>import requests
>>>r = requests.get('https://github.com/timeline.json')
>>>r.json()
注意:成功調用json並不意味響應成功,因為有的服務器會在失敗的響應中包含json對象,這種json會被解碼返回,要檢查請求是否成功,請使用r.raise_for_status 或者檢查r.status_code是否和你期望的相同
原始響應內容
如果你想要獲取來自服務器的原始套接字符響應,你可以使用r.raw,如果你想這么做,請確保在原始請求中設置了stream=True,具體代碼如下:
>>>r = requests.get(https://github.com/timeline.json',stream=Ture)
>>>r.raw
>>>r.raw.read(10)
一般情況下,將以下面的模式將文本流保存到文件
with open(filename,'wb') as fd:
for chunk in r.iter_content(chunk_size):
fd.write(chunk)
定制請求頭
如果你想為http添加頭部,只要傳遞一個dict給headers參數就ok了
>>> url = 'https://github.com/some/endpoint'
>>>headers = {'user-agent':'my-app/0.0.1'}
>>>r = request.get(url,headers=headers)
注意:定制header的優先級低於一些特定的信息源
如果在.netrc中設置了用戶認證信息,使用headers=設置的授權就不會生效,而如果設置了auth=參數,.netrcd的設置就無效了
如果被重定向到別的主機,授權header就會被刪除
代理授權header會被url中提供的代理身份覆蓋掉
在我們能判斷內容長度的情況下,header的Content-Length會被改寫
更加復雜的POST請求
>>>payload = {'key1':'value1','key2':'value2'}
>>>r = requests.post("http://httpbin.org/post",data=payload)
>>>print(r.text)
你還可以為data參數傳入一個元組列表,在表單中多個元素使用同一個key的時候,這個種方式尤其有效
>>> payload=(('key1':'value1'),('key1':'value2'))
>>>r = requests.post("http://httpbin.org/post",data=payload)
>>>print(r.text)
很多是時候你想發送的數據並非編碼為表單形式的,如果你傳遞一個string而不是dict,那數據將會被直接發布出去
如:
>>>import requests
>>> url = 'https://api.github.com/some/endpoint'
>>>payload = {'some':'data'}
>>>r = requests.post(url,data=json.dumps(payload))
除此之外,還可以通過json參數直接傳遞
>>>import requests
>>> url = 'https://api.github.com/some/endpoint'
>>>payload = {'some':'data'}
>>>r = requests.post(url,json=payload)
POST 一個多部分編碼的文件
>>> url = 'http://httpbin.org/post'
>>>files = {'file':open('report.xls','rb')}
>>>r = requests.post(url,files=files)
>>>r.text
響應狀態碼
>>>r = request.get('http://httpbin.org/get')
>>>r.status_code
>>>r.status_code = requests.code.ok #附帶了一個內置的狀態碼查詢
如果發送了一個錯誤請求,可通過Response.raise_for_status()來拋出異常
>>>bad_r = requeest.get("http://httpbin.org/status/404")
>>>bad_r.status_code
>>>bad_r.raise_for_status()
響應頭
>>>r.headers
>>>r.headers['Content-Type']
>>>r.headers.get('content-type')
Cookie 如果響應頭中包含cookie,你可以快速訪問
>>>url = 'http://example.com/some/cookie/setting/url'
>>>r = request.get(url)
>>>r.cookies['example_cookie_name']
發送cookices到服務器,可以使用cookies參數
>>>url = 'http://httpbin.org/cookies'
>>>cookies = dict(cookies_are='working')
>>>r = rquesets.get(url,cookies=cookies)
>>>r.text
cookie 的返回對象為RequestsCookieJar,行為和字典類似,適合誇域名誇路徑使用
>>>jar = requests.cookies.RequestsCookieJar()
>>>jar.set('tasty_cookie','yum',domain='httpbin.org',path='/cookies')
>>>jar.set('gross.cookie','blech',domain='httpbin.org',path='elsewhere')
>>>url = 'http://httpbin.org/cookies'
>>>r = requests.get(url,cookies=jar)
>>>r.text