如何使用 Python 和 Selenium 查找页面中元素的状态?
我们可以借助 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 exposes an executable file
#Through Selenium test we will invoke the executable file which will then #invoke actual browser
driver = webdriver.Chrome(executable_path="C:\chromedriver.exe")
# to maximize the browser window
driver.maximize_window()
#get method to launch the URL
driver.get("https://tutorialspoint.com/selenium/selenium_automation_practice.htm")
#to refresh the browser
driver.refresh()
# identifying the checkbox with xpath
chk =driver.find_element_by_xpath("//*[@value='Automation Tester']")
# printing the status in console
print(chk.is_selected())
# identifying the edit box with xpath
edt =driver.find_element_by_xpath("//*[@name='firstname']")
# printing the display status in console
print(edt.is_displayed())
# identifying the edit box with xpath
edtsts =driver.find_element_by_xpath("//*[@name='lastname']")
# printing the enabled status in console
print(edtsts.is_enabled())
#to close the browser
driver.close()
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP