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

如何使用Selenium验证网页上是否存在复选框列表

使用Selenium验证网页复选框及列表存在性

单个复选框操作示例

以下代码实现定位单个复选框、点击并验证选中状态:

from selenium import webdriver

# 初始化Chrome驱动
driver = webdriver.Chrome(executable_path='../drivers/chromedriver')
# 设置隐式等待时间(5秒)
driver.implicitly_wait(5)
# 打开目标网页
driver.get("https://the-internet.herokuapp.com/checkboxes")

# 通过XPath定位单个复选框
checkbox = driver.find_element_by_xpath("//input[@type='checkbox']")
# 点击复选框
checkbox.click()

# 验证复选框是否选中
if checkbox.is_selected():
    print('Checkbox is checked')
else:
    print('Checkbox is not checked')

# 关闭浏览器驱动
driver.close()

验证复选框列表存在性

若需确认网页上是否存在复选框列表,只需将代码中的find_element_by_xpath替换为find_elements_by_xpath,通过判断返回列表的长度是否大于0即可验证:

from selenium import webdriver

driver = webdriver.Chrome(executable_path='../drivers/chromedriver')
driver.implicitly_wait(5)
driver.get("https://the-internet.herokuapp.com/checkboxes")

# 定位所有复选框,返回元素列表
checkbox_list = driver.find_elements_by_xpath("//input[@type='checkbox']")

# 判断列表长度,验证复选框列表是否存在
if len(checkbox_list) > 0:
    print(f"检测到{len(checkbox_list)}个复选框")
else:
    print("未检测到复选框")

driver.close()

内容的提问来源于stack exchange,提问作者Pankaj Jadhao

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 14:33:19