requests 常见方法总结

时间:2021-08-10 22:32:49

请求设置:requests.get/post

            (

            url,

            data={},

            params={},

            headers={},

            timeout=0.01,

            files={}

             Session() 

                                       verity=False  关闭ssl验证

 proxies={} 代理设置
 auth=HTTPBasicAuth() base认证
           auth=HTTPDigestAuth() digest认证
 

            )

响应获取:response .status_code 

          url 

          cookies

          text

          content    用来保存图片,视频

          json()

 

1.说明

data={}  用于get请求

params={} 用于post请求

 

2.session()用法示例

 场景一:

 

response = requests.get('http://httpbin.org/cookies/set/name/tom')
print(response.text)

response2 = requests.get('http://httpbin.org/cookies')
print(response2.text)

结果:{"cookies": {"name": "tom"}} {"cookies": {}} 获取不到cookie


场景二:
obj = requests.session()
rec = obj.get('http://httpbin.org/cookies/set/name/tom')
print(rec.text)

rec2 = obj.get('http://httpbin.org/cookies')
print(rec2.text)
 
结果:{"cookies": {"name": "tom"}}             {"cookies": {"name": "tom"}} 获取到cookie
 

3.verity用法示例

response = requests.get('https://www.12306.cn',verify=False) 如果不关闭verity会报错
print(response.text.encode("utf8"))

4.代理设置用法

 

proxies = {'http' : '61.135.217.7:80'}
response = requests.get('http://httpbin.org/get', proxies=proxies)
print(response.text)

 

5.auth用法示例

 

import requests
from requests.auth import HTTPBasicAuth
from requests.auth import HTTPDigestAuth

response = requests.get('http://httpbin.org/basic-auth/mother/home', auth=HTTPBasicAuth("mother","home"))
print(response.text)
response2 = requests.get('http://httpbin.org/digest-auth/auth/my_mother/home', auth=HTTPDigestAuth("my_mother","home"))
print(response2.text)

 

 

5.模拟上传图片

file = {'img':open('df.jpg','rb')}
response = requests.post('http://httpbin.org/post',files=file)
print(response.text)

 

 6.字典形式的url拼接

from urllib.parse import urlencode
data = {'city':'北京'}
print("https://www.sojson.com/?%s" % urlencode(data))

 7.例子:unittest + requests + BSTestRunner

  BSTestRunner :形成测试报告的库

1.安装 BSTestRunner 

地址:https://github.com/easonhan007/HTMLTestRunner

将 BSTestRunner.py 文件放入目录 D:\IT\python3\Lib 下

2.开始工程(用例+测试报告)

requests 常见方法总结

 
 
import unittest
import time
from BSTestRunner import BSTestRunner

test_dir = './test_cases'
report_dir = './reports'
discover = unittest.defaultTestLoader.discover(test_dir , pattern="dan.py")
now = time.strftime('%Y-%m-%d %H_%M_%S')
report_name = report_dir+'/'+now+'test_report.html'

with open(report_name,'wb') as f:
runner = BSTestRunner(stream=f,title='Weather API Test Report',description='china wether')
runner.run(discover)