博客
关于我
接口自动化-发送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-laravel框架用户验证(Auth)模块解析(二)注册模块
查看>>
php-laravel框架用户验证(Auth)模块解析(四)忘记密码
查看>>
php-redis中文参考手册_Ping_echo_set_get_setex_psetex_...
查看>>
PHP-Shopify-API-Wrapper 使用教程
查看>>
php-兔子问题,斐波那契数列
查看>>
PHP-希尔排序
查看>>
php-数据结构-二叉树的构建、前序遍历,中序遍历,后序遍历,查找,打印
查看>>
php-有序数组合并后仍有序
查看>>
redis使用
查看>>
Redis以及Redis的php扩展安装
查看>>
PHP-算法-最少比较次数获取最大值最小值
查看>>
php-约瑟夫问题
查看>>
Redis从库不能同步报Can’t save in background: fork: Cannot allocate memory错误
查看>>
Redis从入门到精通|干货篇
查看>>
php.ini maxfileuploads,细说PHP高洛峰文件上传类源文件
查看>>
php.ini中常见的配置信息选项
查看>>
php.ini配置中有10处设置不当,会使网站存在安全问题
查看>>
php/jsp/asp的区别
查看>>
php20个主流框架
查看>>
php301到https,虚拟主机设置自动301跳转到HTTPS
查看>>