如何使用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.com/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();
}
}
}输出
点击运行所有测试 -

点击打开此结果的附加输出链接 -

我们应该获得测试结果和标准输出。

广告
数据结构
网络
关系数据库管理系统(RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP