如何使用Python和Selenium統計頁面中單選按鈕的總數?


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

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

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

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

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

語法

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

示例

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

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 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()

更新於:2020年7月29日

瀏覽量:1K+

啟動你的職業生涯

完成課程獲得認證

開始學習
廣告