博客
关于我
接口自动化-发送get请求-1
阅读量:377 次
发布时间:2019-03-04

本文共 1254 字,大约阅读时间需要 4 分钟。

接口自动化离不开requests模块,它是处理HTTP请求的权威工具。在使用之前,记得先通过pip安装:pip install requests

以下是通过示例展示requests的get方法使用方法:

#coding:utf-8import requestsr = requests.get("https://blog.csdn.net/rhx_qiuzhi/")print(r.status_code)print(r.text)

导入requests后,get方法可以直接访问URL。返回的r对象包含服务器的响应信息。status_code表示状态码,200表示服务器正常响应,但并不意味着接口功能正常。要确认接口是否正常,需要查看返回内容。text属性则提供响应内容的文本形式。

将响应内容保存为文件,可以使用with open命令:

with open("code3.html", "wb") as code:    code.write(r.content)

或者保存为压缩文件:

with open("code3.zip", "wb") as code:    code.write(r.content)

接下来,通过参数请求csdn博客。例如,搜索rhx_qiuzhi:

#coding:utf-8import requestsparams = {"q": "rhx_qiuzhi"}r = requests.get("https://so.csdn.net/so/search/s.do?", params=params)print(r.status_code)print(r.text)with open("code3.html", "wb") as code:    code.write(r.content)

获取百度首页信息时,注意百度首页可能使用gzip压缩:

#coding:utf-8import requestsr = requests.get("https://www.baidu.com")print("状态码:", r.status_code)print("编码格式:", r.encoding)print("响应头:", r.headers)print("内容:", r.content)with open("code3.html", "wb") as code:    code.write(r.content)

response对象的属性包括:

  • status_code: 响应状态码
  • content: 字节流响应体,自动解码压缩格式
  • headers: 响应头字典
  • json(): JSON解码
  • url: 请求URL
  • encoding: 编码格式
  • cookies: 响应cookie
  • raw: 原始响应体
  • text: 解码后的文本内容
  • raise_for_status(): 检查响应状态

记得在处理非200响应时使用raise_for_status()抛出异常。

你可能感兴趣的文章
npm的“--force“和“--legacy-peer-deps“参数
查看>>
npm的安装和更新---npm工作笔记002
查看>>
npm的常用配置项---npm工作笔记004
查看>>
npm的问题:config global `--global`, `--local` are deprecated. Use `--location=global` instead 的解决办法
查看>>
npm编译报错You may need an additional loader to handle the result of these loaders
查看>>
npm设置淘宝镜像、升级等
查看>>
npm设置源地址,npm官方地址
查看>>
npm设置镜像如淘宝:http://npm.taobao.org/
查看>>
npm配置安装最新淘宝镜像,旧镜像会errror
查看>>
NPM酷库052:sax,按流解析XML
查看>>
npm错误 gyp错误 vs版本不对 msvs_version不兼容
查看>>
npm错误Error: Cannot find module ‘postcss-loader‘
查看>>
npm,yarn,cnpm 的区别
查看>>
NPOI
查看>>
NPOI之Excel——合并单元格、设置样式、输入公式
查看>>
NPOI初级教程
查看>>
NPOI利用多任务模式分批写入多个Excel
查看>>
NPOI在Excel中插入图片
查看>>
NPOI将某个程序段耗时插入Excel
查看>>
NPOI格式设置
查看>>