如何在靜態下拉列表中獲取所有選項?


我們可以在 Selenium 中獲得下拉列表中的所有選項。下拉列表中的所有選項都儲存在一個列表資料結構中。這是藉助於 Select 類中的一個方法 options() 實現的。

options() 返回 select 標記下所有選項的列表。如果未在頁面上使用任何定位器標識下拉列表,則返回一個空列表。

語法

d = Select(driver.find_element_by_id("selection"))
o = d.options()

例子

獲取下拉列表中所有選項的程式碼實現。

from selenium import webdriver
from selenium.webdriver.support.select import Select
#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/tutor_connect/index.php")
#to refresh the browser
driver.refresh()
#select class provide the methods to handle the options in dropdown
d = Select(driver.find_element_by_xpath("//select[@name='seltype']"))
#store the options in a list with options method
l = d.options
#to count the number of options and print in console
print(len(l))
#to get all the number of options and print in console
for i in l:
print(i.text)
#to close the browser
driver.close()

更新於: 2020 年 7 月 29 日

659 次瀏覽

開啟您的 職業生涯

完成課程獲得認證

開始
廣告