1. 程式人生 > >python requests介面測試

python requests介面測試

Python 標準庫中的 urllib2 模組提供了你所需要的大多數 HTTP 功能,但是它的 API 太渣了。它是為另一個時代、另一個網際網路所建立的。它需要巨量的工作,甚至包括各種方法覆蓋,來完成最簡單的任務。

總之,大家以後對urllib2庫敬而遠之就行了。來擁抱Requests吧。

Requests的官方文件:http://cn.python-requests.org/zh_CN/latest/

通過下面方法安裝requests

pip install requests

2、Requests如何傳送HTTP請求

非常簡單,先匯入requests,

import requests 

然後,按照下面的方法傳送http的各種請求:

r = requests.get('https://github.com/timeline.json')  
r = requests.post("http://httpbin.org/post")  
r = requests.put("http://httpbin.org/put")  
r = requests.delete("http://httpbin.org/delete")  
r = requests.head("http://httpbin.org/get")   r = requests.options("http://httpbin.org/get")

 

3、為URL傳遞引數

如果http請求需要帶URL引數(注意是URL引數不是body引數),那麼需要將引數附帶到payload字典裡頭,按照下面的方法傳送請求:

import requests  
payload = {'key1': 'value1', 'key2': 'value2'}   r = requests.get("http://httpbin.org/get",params=payload)   print r.url 

通過print(r.url)能看到URL已被正確編碼:

http://httpbin.org/get?key2=value2&key1=value1

注意字典裡值為 None 的鍵都不會被新增到 URL 的查詢字串裡。

 

4、unicode響應內容

import requests  
r = requests.get('https://github.com/timeline.json')  
r.text 

響應結果是:

{"message":"Hello there, wayfaring stranger. If you're reading this then you probably didn't see our blog post a couple of years back announcing that this API would Go away: http://Git.io/17AROg Fear not, you should be able to get what you need from the shiny new Events API instead.","documentation_url":"https://developer.github.com/v3/activity/events/#list-public-events"}


Requests會自動解碼來自伺服器的內容。大多數unicode字符集都能被無縫地解碼。請求發出後,Requests會基於HTTP頭部對響應的編碼作出有根據的推測。當你訪問r.text之時,Requests會使用其推測的文字編碼。你可以找出Requests使用了什麼編碼,並且能夠使用r.encoding 屬性來改變它

>>> r.encoding
'utf-8'

5、二進位制響應內容

如果請求返回的是二進位制的圖片,你可以使用r.content訪問請求響應體。

import requests  
from PIL import Image  
from StringIO import StringIO   r = requests.get('http://cn.python-requests.org/zh_CN/latest/_static/requests-sidebar.png')   i = Image.open(StringIO(r.content))   i.show()  

 

6、JSON響應內容

Requests中也有一個內建的JSON解碼器,助你處理JSON資料:

import requests  
r = requests.get('https://github.com/timeline.json')  
print r.json()

r.json將返回的json格式字串解碼成python字典。r.text返回的utf-8的文字。

7、定製請求頭

如果你想為請求新增HTTP頭部,只要簡單地傳遞一個 dict 給headers 引數就可以了。

import requests  
import  json  
payload = {'some': 'data'}  
headers = {'content-type': 'application/json'}   r = requests.get('https://github.com/timeline.json', data=json.dumps(payload), headers=headers)   print r.json()  

注意,這裡的payload是放到body裡面的,所以params引數要使用json資料。

8、POST請求

就像上面‘定製請求頭’中的例子,將payload序列化為json格式資料,傳遞給data引數。

9、POST提交檔案

先製作一個text檔案,名為‘report.txt’,內容是‘this is a file’。Requests使得上傳多部分編碼檔案變得很簡單:

import requests  
  
url = 'http://httpbin.org/post'  
files = {'file': open('report.txt', 'rb')}   r = requests.post(url, files=files)   print r.text

返回結果是:

C:\Python27\python.exe C:/Users/Administrator/PycharmProjects/flaskexample/postfile.py  
{  
  "args": {},   
  "data": "",   
  "files": {  
    <strong>"file": "this is a file"</strong>     },      "form": {},      "headers": {       "Accept": "*/*",        "Accept-Encoding": "gzip, deflate",        "Content-Length": "160",        "Content-Type": "multipart/form-data; boundary=a3b41a6300214ffdb55ddbc23dfc0d91",        "Host": "httpbin.org",        "User-Agent": "python-requests/2.7.0 CPython/2.7.9 Windows/2012Server"     },      "json": null,      "origin": "202.108.92.226",      "url": "http://httpbin.org/post"   }         Process finished with exit code 0

 

10、POST提交表單

傳遞一個字典給 data 引數就可以了。資料字典在發出請求時會自動編碼為表單形式:

>>> payload = {'key1': 'value1', 'key2': 'value2'}  
>>> r = requests.post("http://httpbin.org/post", data=payload)  

檢視響應內容:

>>> print r.text
{
  "args": {},
  "data": "",   "files": {},   "form": {     "key1": "value1",     "key2": "value2"   },   "headers": {     "Accept": "*/*",     "Accept-Encoding": "gzip, deflate",     "Content-Length": "23",     "Content-Type": "application/x-www-form-urlencoded",     "Host": "httpbin.org",     "User-Agent": "python-requests/2.6.0 CPython/2.7.10 Windows/7"   },   "json": null,   "origin": "124.251.251.2",   "url": "http://httpbin.org/post" }

11、響應狀態碼

使用r.status_code返回響應的狀態碼。

import requests  
  
r = requests.get('http://httpbin.org/get')  
print r.status_code

  為方便引用,Requests還附帶了一個內建的狀態碼查詢物件:

print r.status_code == requests.codes.ok

 

12、失敗請求丟擲異常

如果傳送了一個失敗請求(非200響應),我們可以通過 Response.raise_for_status()來丟擲異常:

import requests  
  
bad_r = requests.get('http://httpbin.org/status/404')  
print bad_r.status_code  
bad_r.raise_for_status()  

返回結果是:

C:\Python27\python.exe C:/Users/Administrator/PycharmProjects/flaskexample/postfile.py  
404  
Traceback (most recent call last):  
  File "C:/Users/Administrator/PycharmProjects/flaskexample/postfile.py", line 5, in <module>  
    bad_r.raise_for_status()  
  File "C:\Python27\lib\site-packages\requests\models.py", line 851, in raise_for_status       raise HTTPError(http_error_msg, response=self)   <strong>requests.exceptions.HTTPError: 404 Client Error: NOT FOUND</strong>      Process finished with exit code 1

  如果返回碼是200,則不會丟擲異常,即:

import requests  
  
bad_r = requests.get('http://httpbin.org/get')  
print bad_r.status_code  
bad_r.raise_for_status()  

的返回結果是:

C:\Python27\python.exe C:/Users/Administrator/PycharmProjects/flaskexample/postfile.py  
200  
  
Process finished with exit code 

 

 

13、響應頭

我們可以檢視以一個Python字典形式展示的伺服器響應頭:

讀取全部頭部:

r.headers  

返回:

{
    'content-encoding': 'gzip',
    'transfer-encoding': 'chunked',
    'connection': 'close',
    'server': 'nginx/1.0.4',
    'x-runtime': '148ms',
    'etag': '"e1ca502697e5c9317743dc078f67693f"',
    'content-type': 'application/json'
}

讀取某一個頭部欄位:

r.headers['Content-Type']  
r.headers.get('content-type')

  

14、Cookies

得到響應中包含的一些Cookie:

>>> url = 'http://example.com/some/cookie/setting/url'  
>>> r = requests.get(url)  
  
>>> r.cookies['example_cookie_name']  
'example_cookie_value'  

要想傳送你的cookies到伺服器,可以使用 cookies 引數:

>>> url = 'http://httpbin.org/cookies'  
>>> cookies = dict(cookies_are='working')  
  
>>> r = requests.get(url, cookies=cookies)  
>>> r.text  

返回結果:

u'{\n  "cookies": {\n    "cookies_are": "working"\n  }\n}\n'

15、重定向與請求歷史

預設情況下,除了 HEAD, Requests會自動處理所有重定向。

可以使用響應物件的 history 方法來追蹤重定向。

>>> r = requests.get('http://github.com')  
>>> r.url  
'https://github.com/'  
>>> r.status_code  
200  
>>> r.history  
[<Response [301]>]  

如果你使用的是GET, OPTIONS, POST, PUT, PATCH 或者 DELETE,,那麼你可以通過 allow_redirects 引數禁用重定向處理:

>>> r = requests.get('http://github.com', allow_redirects=False)  
>>> r.status_code  
301  
>>> r.history  
[]  

如果你使用的是HEAD,你也可以啟用重定向:

>>> r = requests.head('http://github.com', allow_redirects=True)  
>>> r.url  
'https://github.com/'  
>>> r.history  
[<Response [301]>]