使用 Python 爬虫处理表单的核心步骤如下:1. 识别表单元素工具选择:使用浏览器开发者工具(如 Chrome 的 Inspect Element)或 BeautifulSoup 库分析目标网页的 HTML 结构。关键元素::文本框、密码框等(关注 name 和 type 属性)。:下拉列表(需提取选项值)。:多行文本输入。 或 :提交按钮(确认表单的 action URL)。2. 构造表单数据字典格式:将表单字段的 name 属性作为键,待提交数据作为值。data = { "username": "test_user", "password": "123456", "gender": "male" # 示例:下拉列表选项值}动态字段:部分表单可能包含隐藏字段(如 CSRF Token),需从页面中提取:soup = BeautifulSoup(response.text, "html.parser")csrf_token = soup.find("input", {"name": "csrf_token"})["value"]data["csrf_token"] = csrf_token3. 发送表单请求POST 方法:使用 requests.post() 提交数据,需指定表单的 action URL 和构造的 data。import requestsurl = "https://example.com/login"response = requests.post(url, data=data)请求头:部分网站需模拟浏览器行为(如 User-Agent):headers = {"User-Agent": "Mozilla/5.0"}response = requests.post(url, data=data, headers=headers)4. 解析响应根据响应类型选择解析方式:HTML 响应:用 BeautifulSoup 提取数据。soup = BeautifulSoup(response.text, "html.parser")welcome_msg = soup.find("div", {"id": "welcome"}).textJSON 响应:直接加载为字典。json_data = response.json()print(json_data["result"])正则表达式:快速匹配简单文本。import rematch = re.search(r"Welcome, (w+)", response.text)if match: print(match.group(1))完整示例import requestsfrom bs4 import BeautifulSoup# 步骤1:访问表单页面并解析隐藏字段session = requests.Session()login_page = session.get("https://example.com/login")soup = BeautifulSoup(login_page.text, "html.parser")csrf_token = soup.find("input", {"name": "csrf_token"})["value"]# 步骤2:构造表单数据data = { "username": "test_user", "password": "123456", "csrf_token": csrf_token}# 步骤3:提交表单response = session.post("https://example.com/login", data=data)# 步骤4:验证登录并解析结果if "Welcome" in response.text: print("登录成功!") dashboard = session.get("https://example.com/dashboard") soup = BeautifulSoup(dashboard.text, "html.parser") user_info = soup.find("div", {"class": "user-info"}).text print(user_info)else: print("登录失败")注意事项会话保持:使用 requests.Session() 管理登录状态。异常处理:捕获网络请求或解析错误(如 requests.exceptions.RequestException)。合法性:遵守目标网站的 robots.txt 规则,避免高频请求。通过以上步骤,可系统化处理表单提交及后续数据抓取。