如何使用C#和Selenium WebDriver獲取下拉列表中的所有選項?
我們可以使用C#中的Selenium WebDriver獲取下拉列表中的所有選項。HTML程式碼中的靜態下拉列表用select標籤標識。下拉列表的所有選項都帶有option標籤。
為了以列表的形式獲取所有選項,我們首先需要使用任何定位器(例如id、xpath、name等)來識別該元素。然後,我們需要建立一個SelectElement類的物件,並對其應用Options方法。
讓我們研究一下下拉列表的HTML程式碼。
在實現中,我們將使用NUnit框架。
示例
using NUnit.Framework; using OpenQA.Selenium; using OpenQA.Selenium.Firefox; using OpenQA.Selenium.Support.UI; using System; using System.Collections.Generic; using System.Linq; namespace NUnitTestProject1{ public class Tests{ String u = "https://tutorialspoint.tw/selenium/selenium_automation_practice.htm"; IWebDriver d; [SetUp] public void Setup(){ //creating object of FirefoxDriver d = new FirefoxDriver(); } [Test] public void Test1(){ //launching URL d.Navigate() .GoToUrl(u); //identify dropdown IWebElement l = d.FindElement(By.Name("continents")); //object of SelectElement SelectElement s = new SelectElement(l); //Options method to get all options IList<IWebElement> els = s.Options; //count options int e = els.Count; for (int j = 0; j < e; j++){ Console.WriteLine("Option at " + j + " is: " + els.ElementAt(j).Text); } } [TearDown] public void close_Browser(){ d.Quit(); } } }
輸出
點選執行所有測試 -
點選開啟此結果的附加輸出連結 -
我們應該獲得測試結果和標準輸出。
廣告