unittest自动化测试-requests库实现http请求与requests库离线安装

一、requests库离线安装

1.1 安装requests模块所需依赖包

(1)所需依赖包

chardet,idna,urllib3,certifi

(2)下载地址:

https://www.lfd.uci.edu/~gohlke/pythonlibs/

chardet · PyPI

(3)安装方式

pip install xx.whl

pycharm Terminal窗口执行

pip install  certifi-2019.11.28-py2.py3-none-any.whl

pip install  idna-3.1-py3-none-any.whl


 pip install urllib3-1.26.9-py2.py3-none-any.whl

chardet 找不到 none-any版本,下载chardet-3.0.4.tar.gz ,解压后安装:

 python setup.py install

1.2 安装requests模块

requests下载地址:

GitHub - kennethreitz/requests: A simple, yet elegant HTTP library.

解压后,执行

python setup.py install

1.3 测试是否安装成功

(1) python termimal 

输入python ,进入python

输入 ,import requests,无错误即为安装成功。

二、requests使用方法

1、不带参数的 get请求

import requests
# 引入 requests,实现请求
URL = 'http://c.biancheng.net/uploads/course/python_spider/191009.html'
# 输入在浏览器的网址
res = requests.get(URL)
# 发送 GET 方式的请求,并把返回的结果(响应)存储在 res 变量里头
print(res.text)
# res 就是 Response 对象,文本类对象使用.text 把数据转为字符串形式再输出

设置编码格式:

res.encoding = 'utf-8'
# 设置可接收的编码为 utf-8

 打印消息其他:

print(res.status_code)  # 打印状态码
print(res.url)          # 打印请求url
print(res.headers)      # 打印响应头头信息
print(res.text)         #以文本形式打印网页源码

 2、带参数的get请求

import requests
 
url = 'http://httpbin.org/get'
data = {
    'name':'xiaoming',
    'age':'16'
}
response = requests.get(url,params=data)
print(response.url)
print(response.text)

 3、从应答消息中获取json数据

import requests
import json
 
response = requests.get("http://httpbin.org/get")
print(type(response.text))
print(response.json())
//或使用json.loads
print(json.loads(response.text))

4、添加消息头

import requests
 
url = 'https://www.zhihu.com/'
headers = {
    'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36'
}
response = requests.get(url,headers=headers)
print(response.text)

参考文献:

【1】python之requests的基本使用_我行我素,向往自由的博客-CSDN博客_python requests

【2】

离线安装python requests库_A_manda的博客-CSDN博客_python离线安装requests包

你可能感兴趣的:(自动化测试,自动化,http,python)