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

你可能感兴趣的文章
pip 升级报错AttributeError: ‘NoneType’ object has no attribute ‘bytes’
查看>>
pip 安装opencv-python卡死
查看>>
pip 安装出现异常
查看>>
Pip 安装失败:需要 SSL
查看>>
Pip 安装挂起
查看>>
pip 或 pip3 为 Python 3 安装包?
查看>>
pip 文件损坏导致 pip无法使用 报错 ImportError: cannot import name 'main' from 'pip._int
查看>>
pip 无法从 requirements.txt 安装软件包
查看>>
pip/pip3更换国内源
查看>>
pip3 install PyQt5 --user 失败
查看>>
pip3命令全解析:Python3包管理工具的详细使用指南
查看>>
pip3安装命令重复创建文件‘/tmp/pip-install-xxxxx/package‘失败
查看>>
PIPE 接口信号列表
查看>>
pipeline配置与管理Job企业级实战
查看>>
pipeline项目配置实战
查看>>
Pipenv 与 Conda?
查看>>
QVGA/HVGA/WVGA/FWVGA分辨率屏含义及大小//Android虚拟机分辨率
查看>>
pipreqs : 无法将“pipreqs”项识别为 cmdlet、函数、脚本文件或可运行程序的名称。请检查名称的拼写,如果包括路径,请确保路径 正确,然后再试一次。
查看>>
pipy国内镜像的网址
查看>>
quiver绘制python语言
查看>>