如何使用 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.tw/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()
廣告