前言
前面【Locust性能測試2-先登錄場景案例】講了登錄的案例,這種是直接傳賬號和密碼就能登錄了,有些登錄的網站會復雜一點,
需要先從頁面上動態獲取參數,作為登錄接口的請求參數,如【學信網:https://account.chsi.com.cn/passport/login】的登錄接口請求參數
請求參數
需要先發個get請求,從返回的html頁面中解析出需要的數據
- lt : LT-277623-5ldGTLqQhP4foKihHUlgfKPeGGyWVI
- execution: e1s1
備注:
lt 參數是每次打開瀏覽器,訪問登錄首頁時服務端會返回一個新的數據
execution 參數是表示網站刷新次數,可以刷新下再登錄,就變成 e2s1了
<input class="btn_login" name="submit" accesskey="l" value="登錄" tabindex="4" type="submit" title="登錄" />
<div class="account-oprate clearfix">
<a class="find-yhm" href="https://account.chsi.com.cn/account/password!rtvlgname">找回用戶名</a>
<a class="find-mm" href="https://account.chsi.com.cn/account/password!retrive">找回密碼</a>
<a href="https://account.chsi.com.cn/account/preregister.action?from=account-login" class="regist-btn">注冊</a>
</div>
<input type="hidden" name="lt" value="LT-279621-fnisPBt0FVGNFrfWzJJqhTEyw6VkfH" />
<input type="hidden" name="execution" value="e2s1" />
<input type="hidden" name="_eventId" value="submit" />
locustfile3.py代碼
前面用篇專門講了requests實現接口的參數關聯案例,這里直接轉化成locust腳本就行了
# coding:utf-8
from locust import HttpLocust, TaskSet, task
from lxml import etree
class LoginDemo(TaskSet):
'''用戶行為描述'''
def get_it_execution(self):
result = {}
h1 = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36",
}
self.client.headers.update(h1)
r = self.client.get("/passport/login", verify=False)
# 從返回html頁面,解析出lt、execution
dom = etree.HTML(r.content.decode("utf-8"))
try:
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
def login(self, user, psw):
result = self.get_it_execution()
loginurl = "/passport/login"
h2 = {
"Referer": loginurl,
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36",
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
"Origin": "https://account.chsi.com.cn",
"Content-Length": "119",
"Cache-Control": "max-age=0",
"Upgrade-Insecure-Requests": "1",
"Content-Type": "application/x-www-form-urlencoded"
}
body = {
"username": user,
"password": psw,
"rememberMe": "true",
"lt": result["lt"],
"execution": result["execution"],
"_eventId": "submit"
}
self.client.headers.update(h2)
print(self.client.headers)
r1 = self.client.post(loginurl, data=body, verify=False)
# print(r1.text)
@task(1)
def test_login(self):
# 測試數據
user = "13888888888"
psw = "111111"
self.login(user, psw)
class websitUser(HttpLocust):
task_set = LoginDemo
host = "https://account.chsi.com.cn"
min_wait = 3000 # 單位毫秒
max_wait = 6000 # 單位毫秒
if __name__ == "__main__":
import os
os.system("locust -f locustfile3.py")