如何使用 Python 和 Selenium 統計頁面中複選框的數量?


我們可以使用 find_elements 方法來統計 Selenium 中頁面中複選框的總數。在處理任何複選框時,我們總會在 HTML 程式碼中找到一個 type 屬性,其值應為 checkbox。

此特性僅適用於該頁面上的複選框,而不適用於其他型別的 UI 元素,如編輯框、連結等。

要檢索所有具有屬性 type = 'checkbox' 的元素,我們將使用 find_elements_by_xpath() 方法。此方法返回一個包含 xpath 型別為方法引數中指定的 web 元素的列表。如果沒有匹配的元素,則返回一個空列表。

獲取複選框列表後,為了統計其總數,我們需要獲取該列表的大小。列表的大小可以透過列表資料結構的 len() 方法獲得。

最後,此長度將列印到控制檯。

語法

driver.find_elements_by_xpath("//input[@type='checkbox']")

示例

統計複選框的程式碼實現。

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 checkboxes with type attribute in a list
chk =driver.find_elements_by_xpath("//input[@type='checkbox']")
# len method is used to get the size of that list
print(len(chk))
#to close the browser
driver.close()

更新於:2020年7月29日

2K+ 次瀏覽

啟動您的 職業生涯

完成課程獲得認證

開始學習
廣告