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

使用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:

  1. Unnecessary link loop: You don't need to iterate through page links to find the form—you already opened the target URL directly.
  2. Typos: targel_url is misspelled, and interletter is a confusing variable name (let's rename it to target_url for clarity).
  3. Python 3 compatibility: If you're using Python 3, print "Form found!" will throw another error—switch to print("Form found!").
  4. 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 07:22:32