博客
关于我
接口自动化-发送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()抛出异常。

你可能感兴趣的文章
NMAP网络扫描工具的安装与使用
查看>>
NN&DL4.3 Getting your matrix dimensions right
查看>>
NN&DL4.8 What does this have to do with the brain?
查看>>
No 'Access-Control-Allow-Origin' header is present on the requested resource.
查看>>
No fallbackFactory instance of type class com.ruoyi---SpringCloud Alibaba_若依微服务框架改造---工作笔记005
查看>>
No module named cv2
查看>>
No module named tensorboard.main在安装tensorboardX的时候遇到的问题
查看>>
No qualifying bean of type XXX found for dependency XXX.
查看>>
No resource identifier found for attribute 'srcCompat' in package的解决办法
查看>>
No toolchains found in the NDK toolchains folder for ABI with prefix: mips64el-linux-android
查看>>
Node JS: < 一> 初识Node JS
查看>>
Node-RED中实现HTML表单提交和获取提交的内容
查看>>
node.js 怎么新建一个站点端口
查看>>
Node.js 文件系统的各种用法和常见场景
查看>>
node.js 配置首页打开页面
查看>>
node.js+react写的一个登录注册 demo测试
查看>>
Node.js中环境变量process.env详解
查看>>
Node.js安装与配置指南:轻松启航您的JavaScript服务器之旅
查看>>
Node.js的循环与异步问题
查看>>
nodejs libararies
查看>>