如何使用 Selenium 獲取頁面上單選按鈕的總數?


我們可以使用 Selenium webdriver 的 find_elements 方法獲取頁面上單選按鈕的總數。在處理任何單選按鈕時,我們總會在 html 程式碼中找到一個 type 屬性,並且其值應為 radio。

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

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

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

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

語法

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

示例

計算單選按鈕的程式碼實現。

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

更新於: 2021-11-19

1K+ 閱讀量

啟動你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.