欢迎您访问365答案网,请分享给你的朋友!
生活常识 学习资料

初学Requests库

时间:2023-05-26

Requests库是经常被用来做 Web API 接口测试的一个第三方库

pip install requests //安装

request库里的 get方法可以发起一个http 的get请求,也可以调用 post、put、delet

当get函数被用时 发送http请求给服务端后,会返回一个requests库里 定义 的response 类的 实例对象

例如 下面这样就可以打印出bing返回的html内容

import requestsresponse = requests.get('https://cn.bing.com/')print(response.text)

使用Requests发送HTTP请求,url里面的参数可以直接写在url里面

response = requests.get('https://cn.bing.com/search?q=requests&qs=n')

如果 url参数的值包含了 & 这个符号 就把这些参数放到 字典里 然后把字典对象传递给 Requests请求方法的 params 参数里。

a = { 'q':'requests', 'qs':'n&l',}response = requests.get('https://cn.bing.com/search',params=a)

当需要构建请求消息头的时候,把params换成headers就可以 header的值也是字典

构建消息体:Web API接口的消息体基本都是文本 分为三种格式:rlencoded, json, xml

用 XML 格式传输一段信息

import requestsp = '''<?xml version="1.0" encoding="UTF-8"?> '''r = requests.post("http://httpbin.org/post", data=p.encode('utf8'))print(r.text)

urlencoded 格式消息体

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

json 格式消息体

import requests,jsonp= { "O":"牛", "P":"羊%", "Q":[ { "No" : 1, "desc": "问题1...." }, { "No" : 2, "desc": "问题2...." }, ]}r = requests.post("http://httpbin.org/post", data=json.dumps(p))print(r.text)

检查http响应状态码 用reponse 的status_code属性    结果是200(地址不存在就404)属性为int

import requestsresponse = requests.get('https://cn.bing.com/')print(response.status_code)

检查http响应的消息头 通过reponse的headers属性获取(里边的pprint是一个美化打印标准库)

import requests,pprintresponse = requests.get('https://cn.bing.com/')pprint.pprint(dict(response.headers))

检查http响应消息体

import requestsresponse = requests.get('https://cn.bing.com')print(response.text)

响应的消息体 json 格式的居多,通常是吧json转python中的数据对象

(也可以使用json库里的loads函数)但是requests的方法更简单用response对象的json方法

import requestsr = requests.post("http://httpbin.org/post")o = r.json()print(o)

有问题一定要留言告诉我!!我知错就改

Copyright © 2016-2020 www.365daan.com All Rights Reserved. 365答案网 版权所有 备案号:

部分内容来自互联网,版权归原作者所有,如有冒犯请联系我们,我们将在三个工作时内妥善处理。