如何用Locust实现表单提交按钮测试?代码问题修正
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
nameandvalue(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
nameattributes 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 thefilesparameter inself.client.post()instead ofdata.
内容的提问来源于stack exchange,提问作者Alexander Todorovic

