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 0
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]>]
python requests接口测试的更多相关文章
- Python+Requests接口测试教程(1):Fiddler抓包工具
本书涵盖内容:fiddler.http协议.json.requests+unittest+报告.bs4.数据相关(mysql/oracle/logging)等内容.刚买须知:本书是针对零基础入门接口测 ...
- python requests 接口测试
1.get方法请求接口 url:显而易见,就是接口的地址url啦 headers:请求头,例如:content-type = application/x-www-form-urlencoded par ...
- Python+Requests接口测试教程(2):
开讲前,告诉大家requests有他自己的官方文档:http://cn.python-requests.org/zh_CN/latest/ 2.1 发get请求 前言requests模块,也就是老污龟 ...
- Python+Requests接口测试教程(2):requests
开讲前,告诉大家requests有他自己的官方文档:http://cn.python-requests.org/zh_CN/latest/ 2.1 发get请求 前言requests模块,也就是老污龟 ...
- python requests接口测试系列:连接mysql,获取mysql查询的值作为接口的入参
主要思路: 连接mysql数据库,这里数据库需要使用Proxifier来设置代理,然后才能正常连接 获取mysql数据库中某一数据,作为接口的参数信息 将接口返回结果保存至csv数据表中 # -*- ...
- 基于python+requests的简单接口测试
在进行接口测试时,我们可以使用已有的工具(如:jmeter)进行,也可以使用python+requests进行.以下为简单的接口测试模板: 一.提取常用变量,统一配置 新建一个config.py文件, ...
- 基于Python Requests的数据驱动的HTTP接口测试
发表于:2017-8-30 11:56 作者:顾翔 来源:51Testing软件测试网原创 http://www.51testing.com/html/69/n-3720769-2.html ...
- python requests库学习笔记(上)
尊重博客园原创精神,请勿转载! requests库官方使用手册地址:http://www.python-requests.org/en/master/:中文使用手册地址:http://cn.pytho ...
- 转载:python + requests实现的接口自动化框架详细教程
转自https://my.oschina.net/u/3041656/blog/820023 摘要: python + requests实现的接口自动化框架详细教程 前段时间由于公司测试方向的转型,由 ...
随机推荐
- Python3学习之路~2.10 修改haproxy配置文件
需求: .查 输入:www.oldboy.org 获取当前backend下的所有记录 .新建 输入: arg = { 'bakend': 'www.oldboy.org', 'record':{ 's ...
- Openresty 安装第三方插件
Openresty 安装第三方插件 程序媛没有夜生活 2016.08.02 15:33* 字数 167 阅读 1283评论 0喜欢 2 在安装之前,我们先来看一下我们现有的模块. 1.将需要安装的插件 ...
- sort(排序) qsort(快排) bsearch(二分查找)
sort: 一.对int类型数组排序 int a[100]; int cmp ( int a , int b ) //不必强制转换 { return a < b;//升序排列. } sort ( ...
- Py-numpy的随机函数【转载】
转自:https://blog.csdn.net/u012149181/article/details/78913167 1. numpy.random.rand() numpy.random.ran ...
- js 图片区域可点击,适配移动端,图片大小随意改变
实现图片区域可点击,实际上使用map是可以的,但是适配效果并不好,图片只能是固定大小的值,而且点都被写死了. 在这里,我使用的js基于canvas写的一个小工具.可以圈出你需要点击的部分,然后生成一串 ...
- Java Selenium - 元素操作 (二)
一篇概括了常用的元素定位方法,但是找到元素还是不够的,模拟鼠标的操作,完成各个功能点的自动操作才是关键. 下面是常见的页面元素操作会涉及到的方法,不是很全,比较复杂的后面单独拿出来做案例. 一, 输入 ...
- sql server 函数的自定义
创建用户定义函数.这是一个已保存 Transact-SQL 或公共语言运行时 (CLR) 例程,该例程可返回一个值.用户定义函数不能用于执行修改数据库状态的操作.与系统函数一样,用户定义函数可从查询中 ...
- JAVA编程思想学习笔记2-chap4-6-斗之气2段
1.foreach:只能用于数组与容器 2.this指针:内部有个指针指向自己 3.super指针:内部有个指针指向父类部分 4.方法存放于代码区:方法调用时,a.fun()可能会被转换为fun(a) ...
- cocos2dx 3.x(打开网页webView)
#include "ui/CocosGUI.h" using namespace cocos2d::experimental::ui; WebView *webView = Web ...
- Oracle如何查询当前的crs/has自启动状态
我们知道在某些停机测试场景,是需要人为禁用crs/has的自启动的,防止过程中主机反复重启对数据库集群造成影响. 使用crsctl disable/enable crs命令可以禁用/启用crs的自启动 ...