Python接口自动化测试 —— Requests库学习

发布时间:2023年12月18日

安装:

pip install requests

例子:

  1. import requests

  2. r = requests.get('http://www.baidu.com')

  3. print r.status_code

  4. print type(r)

  5. print r.cookies运行程序,得到结果:

运行程序,得到结果:

  1. 200

  2. <class 'requests.models.Response'>

  3. <RequestsCookieJar[<Cookie BDORZ=27315 for .baidu.com/>]>

常用的HTTP请求类型

>>> r = requests.post('http://httpbin.org/post', data = {'key':'value'})
>>> r = requests.put('http://httpbin.org/put', data = {'key':'value'})
>>> r = requests.delete('http://httpbin.org/delete')
>>> r = requests.head('http://httpbin.org/get')
>>> r = requests.options('http://httpbin.org/get')

GET:

?

现在我也找了很多测试的朋友,做了一个分享技术的交流群,共享了很多我们收集的技术文档和视频教程。
如果你不想再体验自学时找不到资源,没人解答问题,坚持几天便放弃的感受
可以加入我们一起交流。而且还有很多在自动化,性能,安全,测试开发等等方面有一定建树的技术大牛
分享他们的经验,还会分享很多直播讲座和技术沙龙
可以免费学习!划重点!开源的!!!
qq群号:822269834

POST:

?API:

request库的返回内容

?返回响应对象

# r.text  当你访问 r.text 之时,Requests 会使用其推测的文本编码
>>> import requests
>>> r = requests.get('https://api.github.com/events')
>>> r.text
u'[{"repository":{"open_issues":0,"url":"https://github.com/...

你可以找出 Requests 使用了什么编码,并且能够使用r.encoding?属性来改变它:

# r.encoding
>>> r.encoding
'utf-8'
>>> r.encoding = 'ISO-8859-1'

二进制响应内容

# 以字节的方式访问请求响应体
>>> r.content
b'[{"repository":{"open_issues":0,"url":"https://github.com/...

Json响应内容

# r.json  JSON 解码失败, r.json() 就会抛出一个异常
>>> import requests
 
>>> r = requests.get('https://api.github.com/events')
>>> r.json()
[{u'repository': {u'open_issues': 0, u'url': 'https://github.com/...

?Raw原始响应内容

# Note:确保在初始请求中设置了 stream=True
>>> r = requests.get('https://api.github.com/events', stream=True)
>>> r.raw
<requests.packages.urllib3.response.HTTPResponse object at 0x101194810>
>>> r.raw.read(10)
'\x1f\x8b\x08\x00\x00\x00\x00\x00\x00\x03'

Header

>>> url = 'https://api.github.com/some/endpoint'
>>> payload = {'key1': 'value1', 'key2': 'value2'}
>>> headers = {'user-agent': 'my-app/0.0.1'}
 
>>> r = requests.get(url, params=payload, headers=headers)

?响应状态码:

>>> r = requests.get('http://httpbin.org/get')
>>> r.status_code
200
 
# 内置的状态码查询对象
>>> r.status_code == requests.codes.ok
True
 
# 发送错误的请求时候,Response.raise_for_status() 来抛出异常
>>> bad_r = requests.get('http://httpbin.org/status/404')
>>> bad_r.status_code
404
 
>>> bad_r.raise_for_status()
Traceback (most recent call last):
  File "requests/models.py", line 832, in raise_for_status
    raise http_error
requests.exceptions.HTTPError: 404 Client Error
 
# 当status_code为200的时候
>>> r.raise_for_status()
None

Cookie:

>>> url = 'http://example.com/some/cookie/setting/url'
>>> r = requests.get(url)
 
>>> r.cookies['example_cookie_name']
'example_cookie_value'
 
# 发送cookie到服务器
>>> url = 'http://httpbin.org/cookies'
>>> cookies = dict(cookies_are='working')
 
>>> r = requests.get(url, cookies=cookies)
>>> r.text
'{"cookies": {"cookies_are": "working"}}'

POST请求例子

传递参数方法:

import requests
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.9.1"
  }, 
  "json": null, 
  "url": "http://httpbin.org/post"
}

?把Json格式的数据传过去

import json
import requests
 
url = 'http://httpbin.org/post'
payload = {'some': 'data'}
r = requests.post(url, data=json.dumps(payload))
print r.text

结果:

{
  "args": {}, 
  "data": "{\"some\": \"data\"}", 
  "files": {}, 
  "form": {}, 
  "headers": {
    "Accept": "*/*", 
    "Accept-Encoding": "gzip, deflate", 
    "Content-Length": "16", 
    "Host": "httpbin.org", 
    "User-Agent": "python-requests/2.9.1"
  }, 
  "json": {
    "some": "data"
  },  
  "url": "http://httpbin.org/post"
}

?如何上传一个文件呢?,新建一个txt文件,内容为:Hello Word!

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

运行结果:

{
  "args": {}, 
  "data": "", 
  "files": {
    "file": "Hello World!"
  }, 
  "form": {}, 
  "headers": {
    "Accept": "*/*", 
    "Accept-Encoding": "gzip, deflate", 
    "Content-Length": "156", 
    "Content-Type": "multipart/form-data; boundary=7d8eb5ff99a04c11bb3e862ce78d7000", 
    "Host": "httpbin.org", 
    "User-Agent": "python-requests/2.9.1"
  }, 
  "json": null, 
  "url": "http://httpbin.org/post"
}

文件就上传成功

另外一种流上传方式:

with open('massive-body') as f:
    requests.post('http://some.url/streamed', data=f)超时:

超时:

# requests 在经过以 timeout 参数设定的秒数时间之后停止等待响应
>>> requests.get('http://github.com', timeout=0.001)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
requests.exceptions.Timeout: HTTPConnectionPool(host='github.com', port=80): Request 

?最后感谢每一个认真阅读我文章的人,看着粉丝一路的上涨和关注,礼尚往来总是要有的,虽然不是什么很值钱的东西,如果你用得到的话可以直接拿走!

?

文章来源:https://blog.csdn.net/2301_77645573/article/details/134958997
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。