使用Mechanize实现表单自动化时出现SyntaxError报错的原因与解决方法
Hey there, let's fix that error and get your form-filling script working properly!
The Root Cause of the SyntaxError
That error pops up because you're trying to assign a value directly to a function call:
br.select_form(name="FirstName")= "Josiah"
select_form() is a method used to choose which form on the page you want to interact with—it's not meant to set field values. Python throws a fit because you can't assign data to the result of a function like that.
How to Correctly Set Form Fields
Once you've selected the right form using select_form(), you set field values using the browser object's index notation, like this:
br["FieldName"] = "YourValue"
Fixing the Rest of Your Script
Your code has a few other small issues we'll clean up too:
- Unnecessary link loop: You don't need to iterate through page links to find the form—you already opened the target URL directly.
- Typos:
targel_urlis misspelled, andinterletteris a confusing variable name (let's rename it totarget_urlfor clarity). - Python 3 compatibility: If you're using Python 3,
print "Form found!"will throw another error—switch toprint("Form found!"). - Duplicate form selection: You called
select_form(nr=0)then tried to call it again for each field, which isn't needed.
Corrected Code
Here's the fixed version with explanations:
import mechanize import re # Initialize the browser br = mechanize.Browser() # Target URL (fixed typo and renamed variable for clarity) target_url = "https://www.w3schools.com/html/html_forms.asp" # Open the target page br.open(target_url) print("Form found!") # Select the first form on the page (or use name="input" for precision, since that's the form's actual name) br.select_form(nr=0) # br.select_form(name="input") # Alternative: use the form's name attribute # Correctly set form field values br["FirstName"] = "Josiah" br["LastName"] = "Loh" # Submit the form and get the result result = br.submit() # Optional: Print the response content to verify submission print(result.read())
Extra Tip
To make form selection more reliable, check the actual HTML of the form you're targeting. The W3Schools form has a name="input" attribute, so using br.select_form(name="input") is better than relying on nr=0 (in case the page ever adds another form before it).
内容的提问来源于stack exchange,提问作者josiah

