Locust学习笔记5——登录接⼝参数关联
  引⾔
  前⾯在讲了登录接⼝,但是这个登录的接⼝并不需要动态参数以及加密签名等校验,⽽且也没有继续讲登录后的操作。现在这篇⽂章主要讲上下接⼝关联的场景,⽐如接⼝A返回的数
据,作为接⼝B的请求参数。
  获取参数
  使⽤抓包⼯具Fiddler,我们登录学信⽹后,可以看到这样的请求参数信息:
  可以看出,每次登录成功,请求参数中都会有lt参数和execution参数,并且每次都不⼀样,
  lt 参数是每次打开浏览器,访问登录⾸页时服务端会返回⼀个新的数据
  execution 参数是表⽰⽹站刷新次数,可以刷新下再登录,就变成其他了
  也就是这两个参数是动态的,那么这两个参数是从哪⾥获取呢?
<input class="btn_login" name="submit" accesskey="l" value="登录" tabindex="4" type="submit" title="登录" />
<div class="account-oprate clearfix">
<a class="find-yhm" href="account.chsi/account/password!rtvlgname">回⽤户名</a>
<a class="find-mm" href="account.chsi/account/password!retrive">回密码</a>
<a href="account.chsi/account/preregister.action?from=account-login" class="regist-btn">注册</a>
</div>
<input type="hidden" name="lt" value="LT-116311-d5aphA2zczml3uQsGczEx2eQVI5TGk-cas" />
jsessionid<input type="hidden" name="execution" value="5ba3ba8a-f18c-40ec-952c-c3fa89815155_ZXlKaGJHY2lPaUpJVXpVeE1pSjkuT0hKd2FVcExORWRoYW00MWEyTldZVEIwYkRoWU9YSlZhbUpTV1hB   
  获取动参代码:
  利⽤lxml爬⾍框架获取html页⾯中的属性对应的值
import requests
from lxml import etree
import urllib3
urllib3.disable_warnings()
s = requests.session()
def get_execution_lt():
"""
获取登录的动态参数
"""
url = 'account.chsi/passport/login'
headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36"}
s.headers.update(headers)
r = s.get(url=url,verify=False)
dom = etree.t.decode('utf-8')) # 返回的是list对象
result = {}
try:
# print(dom.xpath('//*[@id="fm1"]/input[2]')[0].get('value'))
result['lt'] = dom.xpath('//input[@name="lt"]')[0].get('value')
result['execution'] = dom.xpath('//input[@name="execution"]')[0].get('value')
print(result)
except:
print("动态参数lt、execution获取失败!")
return result
if __name__ == '__main__':
login_setup = get_execution_lt()
  运⾏结果:
{'lt': 'LT-124381-CEGJ5JiOi1gm1qYeOXsxPcUiYMRDTi-cas', 'execution': 'e3493856-74e4-4108-89c5-527389da290d_ZXlKaGJHY2lPaUpJVXpVeE1pSjkuYUhCU2ExQjFkV3BHYW10SmVGQkplVFpTU0ZkR1ptaE1U Process finished with exit code 0
  备注:上⾯可以看出,我使⽤了requests.session()⽅法,作⽤是创建⼀个session会话,当你使⽤这个session登录之后,再次使⽤session请求系统其他页⾯的时候,默认使⽤session
会话之前使⽤的cookie参数。例如JSESSIONID
  requests.session()会⾃动保存,这样就实现cookie关联,get_execution_lt()这个函数其实已经获取到了cookies参数。
  登录源码
import requests
from lxml import etree
import urllib3
urllib3.disable_warnings()
import json
s = requests.session()
def get_execution_lt():
"""
获取登录的动态参数
"""
url = 'account.chsi/passport/login'
headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36"}    s.headers.update(headers)
r = s.get(url=url,verify=False)
dom = etree.t.decode('utf-8')) # 返回的是list对象
result = {}
try:
# print(dom.xpath('//*[@id="fm1"]/input[2]')[0].get('value'))
result['lt'] = dom.xpath('//input[@name="lt"]')[0].get('value')
result['execution'] = dom.xpath('//input[@name="execution"]')[0].get('value')
print(json.dumps(result,sort_keys=True,indent=10))
except:
print("动态参数lt、execution获取失败!")
return result
# print(login_setup,111111)
def login_action():
# 登录
url2 = 'account.chsi/passport/login'
body = {
"username":'******',
"password":'*****',
"lt":login_setup['lt'],
"execution":login_setup['execution'],
"_eventId":'submit'
}
h2 = {
"Content-Type": "application/x-www-form-urlencoded"
}
s.headers.update(h2)
# import json,urllib.parse
# data_dic = eval(body)
# data_urlencode = urllib.parse.urlencode(data_dic).encode(encoding='UTF-8')
r2 = s.post(url=url2,data=body)
try:
assert '退出'
print("登录成功")
except:
print("登录失败")
def get_account():
# 登录后请求
r3 = s.get(url='account.chsi/account/account!show')
try:
assert '查看个⼈信息_学信⽹'
print("查询成功")
except:
print("查询失败")
if __name__ == '__main__':
login_setup = get_execution_lt()
login_step = login_action()
check_account = get_account()
  运⾏结果:
  Locust参数关联源码
  由于公司项⽬的⽹站涉及公司保密协议,暂时⽤学信⽹来写这个案例,具体如下代码:
__author__ = 'Leo'
from locust import HttpLocust,TaskSet,task,between
from lxml import etree
import json
import urllib3
urllib3.disable_warnings()
class LoginTest(TaskSet):
"""
定义⽤户⾏为类
"""
def get_execution_lt(self):
"""
获取登录的动态参数
"""
url = '/passport/login'
headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36"}        self.client.headers.update(headers)
r = (url=url,verify=False)
dom = etree.t.decode('utf-8')) # 返回的是list对象
result = {}
try:
# print(dom.xpath('//*[@id="fm1"]/input[2]')[0].get('value'))
result['lt'] = dom.xpath('//input[@name="lt"]')[0].get('value')
result['execution'] = dom.xpath('//input[@name="execution"]')[0].get('value')
print(json.dumps(result,sort_keys=True,indent=10))
except:
print("动态参数lt、execution获取失败!")
return result
def login_action(self,account,password):
# 登录
login_setup = _execution_lt()
url2 = '/passport/login'
body = {
"username":account,
"password":password,
"lt":login_setup['lt'],
"execution":login_setup['execution'],
"_eventId":'submit'
}
h2 = {
"Content-Type": "application/x-www-form-urlencoded"
}
self.client.headers.update(h2)
# import json,urllib.parse
# data_dic = eval(body)
# data_urlencode = urllib.parse.urlencode(data_dic).encode(encoding='UTF-8')
r2 = self.client.post(url=url2,data=body,verify=False)
try:
assert '退出'
print("登录成功")
except:
print("登录失败")
def on_start(self):
account = '****'
password = '***'
self.login_action(account,password)
@task(1)
def get_account(self):
# 登录后请求
r3 = (url='account.chsi/account/account!show')
try:
assert '查看个⼈信息_学信⽹'
print("查询成功")
except:
print("查询失败")
class WebSiteUser(HttpLocust):
task_set = LoginTest
host = "account.chsi"
wait_time = between(3,6)
if __name__ == '__main__':
import os
os.system('locust -f locust_xuexin.py')
  运⾏结果:
  界⾯:
  总结
  到此,以登录后请求其他接⼝的案例已经讲完,在实际项⽬中可以根据这个思路来压测需要登录后的接⼝。有兴趣的朋友可以加⼊测开交流进⾏沟通与学习,⼀起成长!

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。