我一直在尝试加载测试带有一些网络表单的网页。我构建的脚本似乎可以正常工作,因为所有请求都已执行并实际收集了数据:
我面临的问题是网络表单,我想存储我发送的测试模拟用户手动填写网络表单的数据。这是我目前正在构建的脚本:
import requests, logging
from random import seed
from random import randint
from bs4 import BeautifulSoup
from locust import HttpUser, TaskSet, task, events, between
#from locust.clients import HttpSession
from requests.auth import HTTPBasicAuth
class Tests(TaskSet):
wait_time = between(1, 5)
def __init__(self, *args, **kwargs):
super(Tests, self).__init__(*args, **kwargs)
def on_start(self):
""" on_start is called when a Locust start before any task is scheduled """
self.login()
def login(self):
response = requests.get(
"http://127.0.0.1",
auth=HTTPBasicAuth("username", "password")
)
self.client.headers.update(response.request.headers)
# logging.info(response.request.headers)
return response
@task
def testForm(self):
random_number = randint(1, 999)
url = 'form'
data = {
"form_id": "webform_id",
"form_build_id": self.getFormId(url),
"first_name":"test-" + str(random_number),
"last_name":"user" + str(random_number),
"email_address": "test" + str(random_number) + "@user.com",
"op": "Send"
}
self.postFormData(url, data)
def getFormId(self, url):
path = "http://127.0.0.1" + url
response = requests.get(
path,
auth=HTTPBasicAuth("username", "password")
)
content = BeautifulSoup(response.content, "lxml")
form_build_id = content.body.find('input', {'name': 'form_build_id'})['value']
return form_build_id
def postFormData(self, url, data):
self.client.post(url, json=data)
logging.info('Sending data: %s to the form in: /%s', data, url)
class WebUser(HttpUser):
tasks = [Tests]
min_wait = 5000
max_wait = 10000
host = "http://127.0.0.1"
有关代码的一些上下文,首先我必须在页面上进行基本身份验证,然后更新客户端标头,以便在以下任务中登录。
然后执行任务,图表开始显示信息。我添加了日志记录行以检查如何发送请求:
[2021-09-25 16:12:27,800] ubuntu/INFO/root: Sending data: {'form_id': 'webform_id', 'form_build_id': 'form-8PgUKZXFIOq29EPfhTC2U9PqXjHy1dsVImWXHK8U0LI', 'first_name': 'test-262', 'last_name': 'user262', 'email_address': 'test262@user.com', 'op': 'Send'} to the form in: /form
我不确定我错过了什么,或者是否真的可以按照我发送的方式保存这些数据。
更新:
我的错误,在浏览器中尝试并检查我发现我缺少一些帖子正文的参数的发布请求。现在任务如下所示:
@task
def testForm(self):
random_number = randint(1, 999)
url = 'form'
data = {
"first_name":"test-" + str(random_number),
"last_name":"user" + str(random_number),
"email_address": "test" + str(random_number) + "@user.com",
**"source_code": "",
**"webform_type": "petition_template",
"op": "Send",
"form_build_id": self.getFormId(url),
**"form_id": "webform_submission_form",
}
我错过了标有“**”的 3 个参数,不确定“source_code”,但我还是要发送它。关于“form_id”,我使用的是机器名称,这就是没有保存数据的原因。
实际的 webform id 取自网络选项卡中的浏览器开发人员工具。