python WEB接口自动化测试之requests库详解_requests

103 阅读6分钟

r.raise_for_status:失败请求(非200响应)抛出异常。

1.4举例说明

payload={'key1':'value1','key2':'value2'}
r=requests.get("httpbin.org/get",params…)
r.status_code
200
r.json()

{u'origin': u'113.98.252.236', u'headers': {u'Host': u'httpbin.org', u'Accept-Encoding': u'gzip, deflate', u'Accept': u'*/*', u'User-Agent': u'python-requests/2.7.0 CPython/2.7.11 Windows/7'}, u'args': {u'key2': u'value2', u'key1': u'value1'}, u'url': u'httpbin.org/get?key2=va…

r.url  #url:params数据会以键/值对的形式置于 URL 中,跟在一个问号的后面。
u'httpbin.org/get?key2=va…'
r.headers

{'content-length': '334', 'server': 'nginx', 'connection': 'keep-alive', 'access-control-allow-credentials': 'true', 'date': 'Fri, 09 Dec 2016 09:04:40 GMT', 'access-control-allow-origin': '*', 'content-type': 'application/json'}

r.headers['content-type']
'application/json'
r.raw
<requests.packages.urllib3.response.HTTPResponse object at 0x0000000002E64E10>
r.cookies
<RequestsCookieJar[]>
r.text

u'{\n "args": {\n "key1": "value1", \n "key2": "value2"\n }, \n "headers": {\n "Accept": "*/*", \n "Accept-Encoding": "gzip, deflate", \n "Host": "httpbin.org", \n "User-Agent": "python-requests/2.7.0 CPython/2.7.11 Windows/7"\n }, \n "origin": "113.98.252.236", \n "url": "httpbin.org/get?key2=va…'

r.content

'{\n "args": {\n "key1": "value1", \n "key2": "value2"\n }, \n "headers": {\n "Accept": "*/*", \n "Accept-Encoding": "gzip, deflate", \n "Host": "httpbin.org", \n "User-Agent": "python-requests/2.7.0 CPython/2.7.11 Windows/7"\n }, \n "origin": "113.98.252.236", \n "url": "httpbin.org/get?key2=va…'

payload = {'key1': 'value1', 'key2': 'value2'}

r = requests.get("httpbin.org/get", params=payload,stream=True)

r.raw

<requests.packages.urllib3.response.HTTPResponse object at 0x0000000003105940>

r.raw.read()

'{\n  "args": {\n    "key1": "value1", \n    "key2": "value2"\n  }, \n  "headers": {\n    "Accept": "*/*", \n    "Accept-Encoding": "gzip, deflate", \n    "Host": "httpbin.org", \n    "User-Agent": "python-requests/2.7.0 CPython/2.7.11 Windows/7"\n  }, \n  "origin": "113.98.252.236", \n  "url": "httpbin.org/get?key2=va…'

1.5用fiddler查看抓包情况

r.json():json数据,可以看出与1.4中的r.json()值一致。

r.headers:响应头数据,可以看出与1.4中r.headers值一致。

r.raw:响应****原始数据

1.6 get请求总结

    综上所述,通过requests.get("某url",params={字典类型参数键值对})模拟浏览器发送一个http的请求(其中请求的方法是get,请求的url地址如下形式

httpbin.org/get?key2=va…

2.POST请求****

点击返回目录

2.1查看post函数的使用

**>>> help(requests.post)          #**查看requests库的属性post请求函数的使用

post(url, data=None, json=None, **kwargs)
Sends a POST request.

:param url: URL for the new :class:Request object.
:param data: (optional) Dictionary, bytes, or file-like object to send in the body of the :class:Request.
:param json: (optional) json data to send in the body of the :class:Request.
:param \*\*kwargs: Optional arguments that request takes.
:return: :class:Response <Response> object
:rtype: requests.Response

2.2 requests的post****函数的入参说明

url:调用接口的URL地址。

data:为可选参数,该参数是一个字典类型。

json:为可选参数,该参数是一个json类型。

**kwargs:其他可选参数,例如headers等。

2.3 requests****函数的返回值(http响应)

同1.3

json():生成json数据对象的方法。如果 JSON 解码失败, r.json 就会抛出一个异常。例如,响应内容是 401 (Unauthorized),尝试访问 r.json 将会抛出 ValueError: No JSON object could be decoded 异常。

status_code:响应状态码。

encoding:编码,如utf-8。

url:目标url。

headers:响应头。类型为字典类型,若键不存在则返回None。

text:响应内容。字符串方式,会自动根据响应头部的字符编码进行解码。如果你改变了编码r.encoding,每当你访问 r.text ,Request 都将会使用 r.encoding 的新值。

content:二进制响应内容。字节方式,会自动为你解码gzip和deflate压缩。

raw:原始响应内容,也就是 urllib 的 response 对象,请求中要加stream=True,再使用 r.raw.read() 读取。

r.raise_for_status:失败请求(非200响应)抛出异常。

2.4举例说明

payload = {'key1': 'value1', 'key2': 'value2'}

r = requests.post("httpbin.org/post", data=payload)

r.status_code

200

r.json()

{u'files': {}, u'origin': u'113.98.252.236', u'form': {u'key2': u'value2', u'key1': u'value1'}, u'url': u'httpbin.org/post', u'args': {}, u'headers': {u'Content-Length': u'23', u'Accept-Encoding': u'gzip,deflate', u'Accept': u'*/*', u'User-Agent': u'python-requests/2.7.0 CPython/2.7.11 Windows/7', u'Host': u'httpbin.org', u'Content-Type': u'application/x-www-form-urlencoded'}, u'json': None, u'data': u''}

r.url

u'httpbin.org/post'

r.headers

{'content-length': '461', 'server': 'nginx', 'connection': 'keep-alive', 'access-control-allow-credentials': 'true', 'date': 'Mon, 12 Dec 2016 02:46:14 GMT', 'access-control-allow-origin': '*', 'content-type': 'application/json'}

r.headers['content-type']

'application/json'

r.raw

<requests.packages.urllib3.response.HTTPResponse object at 0x0000000002EE4A58>

r.text

u'{\n  "args": {}, \n  "data": "", \n  "files": {}, \n  "form": {\n    "key1": "value1", \n    "key2": "value2"\n  }, \n  "headers": {\n    "Accept": "*/*", \n    "Accept-Encoding": "gzip, deflate", \n    "Content-Length": "23", \n    "Content-Type": "application/x-www-form-urlencoded", \n    "Host": "httpbin.org", \n    "User-Agent": "python-requests/2.7.0 CPython/2.7.11 Windows/7"\n  }, \n  "json": null, \n  "origin": "113.98.252.236", \n  "url": "httpbin.org/post"\n}\n'

r.content

'{\n  "args": {}, \n  "data": "", \n  "files": {}, \n  "form": {\n    "key1": "value1", \n    "key2": "value2"\n  }, \n  "headers": {\n    "Accept": "*/*", \n    "Accept-Encoding": "gzip, deflate", \n    "Content-Length": "23", \n    "Content-Type": "application/x-www-form-urlencoded", \n    "Host": "httpbin.org", \n    "User-Agent": "python-requests/2.7.0 CPython/2.7.11 Windows/7"\n  }, \n  "json": null, \n  "origin": "113.98.252.236", \n  "url": "httpbin.org/post"\n}\n'

payload = {'key1': 'value1', 'key2': 'value2'}

#获取原始响应内容

r = requests.post("httpbin.org/post", data=payload,stream=True)

r.raw

<requests.packages.urllib3.response.HTTPResponse object at 0x0000000003105208>

r.raw.read()

'{\n  "args": {}, \n  "data": "", \n  "files": {}, \n  "form": {\n    "key1": "value1", \n    "key2": "value2"\n  }, \n  "headers": {\n    "Accept": "*/*", \n    "Accept-Encoding": "gzip, deflate", \n    "Content-Length": "23", \n    "Content-Type": "application/x-www-form-urlencoded", \n    "Host": "httpbin.org", \n    "User-Agent": "python-requests/2.7.0 CPython/2.7.11 Windows/7"\n  }, \n  "json": null, \n  "origin": "113.98.252.236", \n  "url": "httpbin.org/post"\n}\n'

#使用 json 参数直接传递

payload = {'key1': 'value1', 'key2': 'value2'}

r = requests.post("httpbin.org/post", json=payload)

r.text

u'{\n  "args": {}, \n  "data": "{\"key2\": \"value2\", \"key1\": \"value1\"}", \n  "files": {}, \n  "form": {}, \n  "headers": {\n    "Accept": "*/*", \n    "Accept-Encoding": "gzip, deflate", \n    "Content-Length": "36", \n    "Content-Type": "application/json", \n    "Host": "httpbin.org", \n    "User-Agent": "python-requests/2.7.0 CPython/2.7.11 Windows/7"\n  }, \n  "json": {\n    "key1": "value1", \n    "key2": "value2"\n  }, \n  "origin": "113.98.252.236", \n  "url": "httpbin.org/post"\n}\n'

2.5用fiddler查看抓包情况

r.json():json数据,可以看出与2.4中的r.json()值一致。

注:通过json进行传参的json数据

r.headers:响应头数据,可以看出与2.4中r.headers值一致。

r.raw:响应****原始数据

2.6 post请求总结

    综上所述,通过requests.post("某url",data={字典类型参数键值对})模拟浏览器发送一个http的请求(其中请求的方法是post,请求的url地址如下形式

httpbin.org/get),服务器处理数…

3.其他用法

点击返回目录

3.1 定制请求头

payload = {'key1': 'value1', 'key2': 'value2'}
headers = {'user-agent': 'my-app/0.0.1'}
r = requests.post("httpbin.org/post", data=payload,headers=headers)

用fiddler抓包,可以看到,发送请求的请求头中的user-agent的值为设置的值。

注意: 所有的 header 值必须是 string、bytestring 或者 unicode。

3.2上传文件

import os

os.getcwd()

'D:\pythontest'

f=open('1.txt','w+')

f.write('test') 

os.listdir('D:\pythontest')

['1.txt',]

import requests

url = 'httpbin.org/post'

files = {'file': open('1.txt', 'rb')}

r = requests.post(url, files=files) 

r.text

u'{\n  "args": {}, \n  "data": "", \n  "files": {\n    "file": ""\n  }, \n  "form": {}, \n  "headers": {\n    "Accept": "*/*", \n    "Accept-Encoding": "gzip, deflate", \n    "Content-Length": "141", \n    "Content-Type": "multipart/form-data; boundary=37de3eb22a754f34849771891b77bd23", \n    "Host": "httpbin.org", \n    "User-Agent": "python-requests/2.7.0 CPython/2.7.11 Windows/7"\n  }, \n  "json": null, \n  "origin": "113.98.252.236", \n  "url": "httpbin.org/post"\n}\n'

用fiddler抓包,可以看到,响应的JSON数据中有file。

3.3 cookies的发送

url = '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'

4.知识拓展

点击返回目录

4.1关于GET和POST的区别