You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Locust实现表单提交按钮测试?代码问题修正

Fixing Form Submission Simulation in Your Locust Test

Hey there! Let's get that form submit button simulation working correctly. The issue with your current code is that it's only sending a single key-value pair, but real form submissions need to match all the parameters the actual frontend form sends—including the submit button's exact name and value attributes, plus any other required fields (like input values or CSRF tokens).

Step 1: Inspect the Actual Form

First, open your target website in a browser, right-click the form, and select "Inspect" to view the HTML. Look for:

  • The submit button's name and value (e.g., <button type="submit" name="submit_btn" value="Send Message">Submit</button>)
  • Any other input fields in the form (text inputs, hidden fields like CSRF tokens)

Step 2: Update the Locust Task

Here's how to adjust your index task to properly simulate the button click:

Basic Form Submission (No CSRF Token)

If your form doesn't require a CSRF token, just include all form fields plus the submit button's parameters:

@task(2)
def index(self):
    # Match the exact field names and values from your form's HTML
    form_payload = {
        # Example: If there's a text input with name="greeting"
        "greeting": "Good morning",
        # Submit button's name and value (copy from your form's HTML)
        "submit_btn": "Send Message"
    }
    # Send the POST request with the full form data
    self.client.post("/", data=form_payload)

Form Submission with CSRF Token

Most modern sites use CSRF tokens to prevent attacks. You'll need to first fetch the page to get the token, then include it in your POST request:

@task(2)
def index(self):
    # First, get the page to retrieve the CSRF token
    page_response = self.client.get("/")
    
    # Extract the token from the page (adjust the selector to match your site)
    # This uses Locust's built-in HTML parsing via BeautifulSoup
    csrf_token = page_response.html.find("input[name='csrf_token']").first.value
    
    # Build the full form payload including the token and submit button
    form_payload = {
        "greeting": "Good morning",
        "submit_btn": "Send Message",
        "csrf_token": csrf_token
    }
    
    # Submit the form
    self.client.post("/", data=form_payload)

Key Notes

  • Always use the exact name attributes from your form's HTML—this is how the server identifies which fields are being submitted, including the button click.
  • If your form uses multipart/form-data (for file uploads), use the files parameter in self.client.post() instead of data.

内容的提问来源于stack exchange,提问作者Alexander Todorovic

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 07:33:44