如何使用 Python 在 Selenium 中查找页面中元素的状态?
selenium web driverautomation testingsoftware testing更新于 2026/2/14 13:52:17
我们可以借助 Selenium 查找页面中元素的状态。我们可以获取元素是启用还是禁用的信息。此外,我们还可以验证元素是否在屏幕上可见以供用户交互。
网页上可能有许多复选框或单选按钮。Selenium 提供了一种方法来检查这些 UI 元素是否处于选中状态。
有多种方法可以验证元素的状态。它们列于下方 −
is_selected()
此方法验证元素(复选框、单选按钮)是否处于选中状态。返回布尔值 TRUE 或 FALSE。
语法 −
driver.find_element_by_class_name("prom").is_selected()
is_dispayed()
此方法验证元素是否对用户可见。返回布尔值 TRUE 或 FALSE。
语法 −
driver.find_element_by_class_name("prom").is_displayed()
is_enabled()
此方法验证元素是否处于启用状态。返回布尔值 TRUE 或 FALSE。
语法 −
driver.find_element_by_class_name("prom-user").is_enabled()
示例
使用上述方法的代码实现。
from selenium import webdriver
#browser 公开一个可执行文件
#通过 Selenium 测试,我们将调用该可执行文件,然后 #调用实际的浏览器
driver = webdriver.Chrome(executable_path="C:\chromedriver.exe")
# 最大化浏览器窗口
driver.maximize_window()
#获取方法启动URL
driver.get("https://www.tutorialspoint.com/selenium/selenium_automation_practice.htm")
# 刷新浏览器
driver.refresh()
# 使用 xpath 识别复选框
chk =driver.find_element_by_xpath("//*[@value='Automation Tester']")
# 在控制台中打印状态
print(chk.is_selected())
# 使用 xpath 识别编辑框
edt =driver.find_element_by_xpath("//*[@name='firstname']")
# 在控制台中打印显示状态
print(edt.is_displayed())
# 使用 xpath 识别编辑框
edtsts =driver.find_element_by_xpath("//*[@name='lastname']")
# 在控制台中打印启用状态
print(edtsts.is_enabled())
# 关闭浏览器
driver.close()

