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

你可能感兴趣的文章
PHP 学习笔记 (四)
查看>>
Redis入门概述
查看>>
php 实现Iterator 接口
查看>>
PHP 实现N阶矩阵相乘
查看>>
php 实现进制转换(二进制、八进制、十六进制)互相转换
查看>>
PHP 实现页面跳转的三种方式及详细解析
查看>>
php 将XML对象转化为数组
查看>>
PHP 工具
查看>>
php 常用方法
查看>>
PHP 并发扣款,保证数据一致性(悲观锁和乐观锁)
查看>>
php 延迟静态绑定static关键字
查看>>
php 引用 -
查看>>
Redis入门
查看>>
PHP 截取字符串乱码的解决方案
查看>>
php 接口类与抽象类的实际作用
查看>>
PHP 插入排序 -- 折半查找
查看>>
PHP 支持8种基本的数据类型
查看>>
php 放大镜,放大镜放大图片效果
查看>>
php 数据库 表格数据,php数据库到excel表格-php怎么把数据库数据放到表格里
查看>>
PHP 数据库连接池实现
查看>>