目录
1、介绍及安装
dos命令行安装: pip install requests
dos命令行验证: pip show requests
pycharm导入requests
从代码中导入:import requests
2、使用requests发送get请求
2.1、使用requests发送不带参数的get请求
以访问百度为例,访问百度时,是使用的get请求,所以这里调用requests.get()方法,将返回结果用resp接收,这里因为响应结果是乱码,所以这里把返回结果编码设置为utf-8
import requests
def fun1():
resp = requests.get("http://www.baidu.com") #request发送不带参数的get请求
resp.encoding="utf-8" #防止中文乱码,设置响应内容编码格式
print(resp.status_code) #输出响应状态码
print(resp.text) #获取响应的文本信息
if __name__ == "__main__":
fun1()
2.2、使用requests发送带参数的get请求
还是以访问百度为例,这里是在百度搜索python,后面增加了一个参数wd,也可以直接用
resp = requests.get("http://www.baidu.com/s?wd=python"),下面把url和请求参数分别用变量接受,在请求中使用变量,这种写法比较直观
#发送get请求带参数--请求格式为字典,使用params参数
def fun2():
data_dict={"wd":"python"}
req_url="http://www.baidu.com/s"
resp = requests.get(url=req_url,params=data_dict)
print(resp.status_code)
3、使用requests发送post请求
post请求的参数分为两种情况,请求头中Content-type是application/x-www.form-url,后面的参数就是data,请求头中Content-type是application/json,参数就用json,
response = request.post(url,data=None,json=None)
param url : 请求的url
param data:(可选) 表单形式请求头中Content-type:application/x-www.form-url
param json: (可选) 参数接收json数据时,Content-Type:application/json
说明:
-
data:参数接收form表单数据,后台会自动附加form表单请求信息头
header={"Content-Type":"application"}
-
json:参数接收json数据时,后台会自动附加json表单请求信息头
header={“Content-Type”:“application/json”}
随意抓取一个post请求接口,这个接口请求头中是Content-type:application/json,那么使用requests发送接口请求参数就用json。
3.1、data参数提交数据
请求TPshop项目的登录接口 请求数据(username:13088888888 password:123456 verify_code:1234
登录接口URL:http://localhost/index.php?m=Home&c=User&a=do_login请求头中Cont