发送HTTP请求
导入requests库并将测试的接口地址设为变量
import requests
base_url = 'http://httpbin.org'
Get请求
r =requests.get(base_url+'/get')
print(r.status_code)
Post请求
r=requests.post(base_url+'/post')
print(r.status_code)
Put请求
r=requests.put(base_url+'/put')
print(r.status_code)
Delete请求
r=requests.delete(base_url+'/delete')
print(r.status_code)
Get传入参数
param_data = {'user':'zxw','password':'666'}
r =requests.get(base_url+'/get',params=param_data)
print(r.url)
print(r.status_code)
Post传入参数
form_data = {'user':'zxw','password':'666'}
r=requests.post(base_url+'/post',data=form_data)
print(r.text)
header请求头设置
headers = {
'User-Agent':'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.108 Safari/537.36'}
r = requests.get("https://www.zhihu.com/",headers=headers)
print(r.status_code)
print(r.text)
Cookies设置
items() 作用:将列表转为元组
cookie={'user':'zxc'}
s = requests.Session()
r = s.get(base_url+'/cookies/set/user/51zxw')
print(r.text)
r = s.get(base_url+'/cookies')
print(r.text)
r = requests.get('http://www.baidu.com')
print(r.cookies)
print(type(r.cookies))
for key,value in r.cookies.items():
print(key+':'+value)
超时设置
timeout 是等待时间,超过等待时间没有回应就会报错,下列代码设置为特别短的时间。
cookie={'user':'zxc'}
r = requests.get(base_url+'/cookies',cookies=cookie,timeout=0.003)
print(r.text)
上传文件
file = {'file':open('C:\\Users\\sam\\Desktop\\scre\\test.jpg','rb')}
r = requests.post(base_url+'/post',files=file)
print(r.text)
关闭验证SSL
r = requests.get('https://www.12306.cn',verify=False)
print(r.text)
代理设置
proxies = {'http':'http://219.141.153.41:80'}
r = requests.get(base_url+'/get',proxies=proxies)
print(r.text)
身份认证
from requests.auth import HTTPBasicAuth
from requests.auth import HTTPDigestAuth
#身份认证-BasicAuth
r = requests.get(base_url+'/basic-auth/51zxw/8888',auth=HTTPBasicAuth('51zxw','8888'))
print(r.text)
#身份认证-DigestAuth
r = requests.get(base_url+'/digest-auth/auth/51zxw/8888',auth=HTTPDigestAuth('51zxw','8888'))
print(r.text)
流式请求
import json
r = requests.get(base_url+'/stream/10',stream=True)
if r.encoding is None:
r.encoding = 'utf-8'
for line in r.iter_lines(decode_unicode=True):
if line:
data = json.loads(line)
print(data['id'])
接口测试模板
import requests
from urllib import parse
import json
#g构造接口测试数据
data = {'city':'北京'}
city = parse.urlencode(data).encode('utf-8')
url = 'http://t.weather.sojson.com/api/weather/city/101030100'
#发送请求
r = requests.get(url,params=city)
#将返回结果转化为Json类型
response_data = r.json()
#分别获取日期,相应信息,状态,城市
print(response_data['date'])
print(response_data['message'])
print(response_data['status'])
#print(response_data['cityInfo'][0]['city'])
#获取当日天气
print(response_data['data']['forecast'][0]['date'])
print(response_data['data']['forecast'][0]['type'])
print(response_data['data']['forecast'][0]['high'])
print(response_data['data']['forecast'][0]['low'])
以上转自:https://blog.csdn.net/m0_37193944/article/details/88725946
遇到的问题
报错1:requests.exceptions.SSLError: HTTPSConnectionPool(host='console.box.lenovo.com', port=443): Max retries exceeded with url: /v2/user/login_new (Caused by SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate in certificate chain (_ssl.c:1108)')))
解决方法
# 请求里加个参数verify=False
r = requests.post(url, data, verify=False)
报错2:Unverified HTTPS request is being made to host '127.0.0.1'. Adding certificate verification is strongly advised
解决方法
# 在请求前加上下面的语句
requests.packages.urllib3.disable_warnings()
# 请求
r = requests.post(url,data)