天天看点

Requests发送get、post请求

使用Requests发送无参数的get请求

  1. 安装Requests库pip install requests
  2. 导入requests模块
  3. 构造接口地址
  4. 创建一个名为res的response对象
  5. 发送请求,使用requests.get(url)即可完成
  6. 打印响应结果

案例:

  1. 请求地址:https://www.v2ex.com/
  2. 请求方式:get
  3. 请求参数:无
Requests发送get、post请求

响应并打印结果

Requests发送get、post请求
Requests发送get、post请求

使用Requests发送有请求头的get请求步骤如下:

  1. 导入requests库
  2. 构造URL地址
  3. 构造请求参数,定义一个表示请求头部信息的字典
  4. 发送请求的时候,使用requests.get(url=tar_url,headers=需要携带的头部信息参数);
  5. 打印响应结果

案例:

  1. 请求地址:https://www.v2ex.com/
  2. 请求方式:get
  3. 请求头:"Host": "www.v2ex.com","Accept": "*/*","Accept-Encoding": "gzip, deflate, br"
  4. 请求参数:无
Requests发送get、post请求

响应并打印结果:

Requests发送get、post请求
Requests发送get、post请求

使用Requests发送有请求参数的get请求步骤如下:

  1. 导入requests库
  2. 构造URL地址
  3. 构造请求参数
  4. 发送请求的时候,使用requests.get(url=tar_url,params=需要携带的请求参数);params:字典类型,指定请求参数,常用于发送get请求时使用
  5. 打印结果

案例:

  1. 请求地址:https://www.v2ex.com/api/members/show.json
  2. 请求方式:get
  3. 请求头:无
  4. 请求参数:id:12306
Requests发送get、post请求

响应并打印结果:

Requests发送get、post请求

requests实现参数化

  1. 导入requests库;
  2. 构造URL地址;
  3. 加上一个for循环;
  4. 定义请求参数ID循环12次
  5. 打印结果
Requests发送get、post请求

响应并打印结果:

Requests发送get、post请求

发送带有请求头、请求参数的Post请求步骤如下:

  1. 导如requests包
  2. 构造URL地址
  3. 设置请求头content-tepe application/x-www-form-urlencoded
  4. 构造请求参数
  5. 发送请求,post请求传递参数时使用data=
  6. 打印响应结果

案例:

  1. 请求地址:http://api.fanyi.baidu.com/api/trans/vip/translate
  2. 请求方式:post
  3. 请求头:content-tepe application/x-www-form-urlencoded
  4. 请求参数:q/from/to/appid/salt/sign
Requests发送get、post请求

响应并打印结果:

Requests发送get、post请求