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

Selenium如何验证被<a>与<i>标签包裹的复选框选中状态?

解决模拟复选框的选中状态识别问题

核心问题在于:你调用is_selected()的目标是<i>标签,这不是标准的表单复选框元素,该方法仅对<input type="checkbox">这类表单元素有效。页面上的可视化复选框是用<i>模拟的,真正控制选中状态的是隐藏的input[@name='non_stop']元素,必须对它调用is_selected()才能获取真实状态。

修正后的代码示例

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

driver = webdriver.Chrome()
driver.get("https://www.yatra.com/")

# 定位实际存储状态的隐藏input元素
non_stop_checkbox = driver.find_element(By.XPATH, "//input[@name='non_stop']")
# 定位页面上可点击的可视化元素(i标签)
non_stop_toggle = driver.find_element(By.XPATH, "//input[@name='non_stop']/preceding-sibling::i")

print("Before clicking")
print(non_stop_checkbox.is_selected())  # 正确返回False

non_stop_toggle.click()
# 用WebDriverWait替代sleep,等待选中状态变化,提升稳定性
WebDriverWait(driver, 5).until(EC.element_selection_state_to_be(non_stop_checkbox, True))

print("After clicking")
print(non_stop_checkbox.is_selected())  # 正确返回True

driver.quit()

补充说明

  • 页面模拟的复选框(<i>/<a>标签)仅负责视觉展示和交互触发,实际的选中/未选中状态由对应的隐藏<input>元素维护。
  • 替换sleep()为WebDriverWait可以避免固定等待时间的低效和不稳定,确保状态变化后再执行后续操作。

内容的提问来源于stack exchange,提问作者VishwasR Vibhu

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 03:57:50