![](/img/trans.png)
[英]How to select an option from drop down using Selenium WebDriver C#?
[英]Select each option in a drop down using Selenium WebDriver C#
我無法在下拉列表中選擇選項。 我想我需要.Select
或SelectElement
,但沒有這樣的選擇。
示例代碼:
IWebDriver ffbrowser = new FirefoxDriver();
ffbrowser.Navigate().GoToUrl("http://www.amazon.com/");
ffbrowser.Manage().Window.Maximize();
Thread.Sleep(500);
IWebElement ddl = ffbrowser.FindElement(By.Name("url"));
int numofitems = ddl.FindElements(By.TagName("option")).Count;
for (int i = 1; i < numofitems; i++)
{
ffbrowser.select("TagName = option", "index = i");
}
“ffbrowser.select”中的“select”報告為錯誤:
錯誤1'OpenQA.Selenium.IWebDriver'不包含'select'的定義,也沒有擴展方法'select'接受類型'OpenQA.Selenium.IWebDriver'的第一個參數(你是否缺少using指令或者裝配參考?)
我的項目參考包括Selenium.WebDriverBackedSelenium
, Thoughtworks.Selenium.Core
, WebDriver
, WebDriver.Support
我有
using NUnit.Framework;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Firefox;
using OpenQA.Selenium.IE;
using OpenQA.Selenium.Support.UI;
根據您使用的Selenium WebDriver的版本,您可以使用SelectElement
類,該類將包含在OpenQA.Selenium.Support.UI
。
例如:
SelectElement selector = new SelectElement(element);
selector.SelectByIndex(1);
元素是你的下拉框。
下面是一個示例,可以更好地說明如何獲取下拉列表中的所有項目以及從下拉列表中選擇項目。
下拉列表的示例Html代碼
<select>
<option>Milk</option>
<option>Coffee</option>
<option>Tea</option>
</select>
下面的代碼從上面的下拉列表中獲取所有項目,並選擇項目'Coffee'。代碼的邏輯如下
步驟1.創建web元素標記的界面步驟2.使用web元素標記的所有子元素創建IList步驟3.選擇Drop List項“Coffee”
using System;
using System.Collections.Generic;
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
using OpenQA.Selenium.Support.UI;
namespace SeleniumTests
{
class DropDownListSelection
{
static void Main(string[] args)
{
IWebDriver driver = new FirefoxDriver();
driver.Navigate().GoToUrl("http://DropDownList.html");
IWebElement element = driver.FindElement(By.XPath("//Select"));
IList<IWebElement> AllDropDownList = element.FindElements(By.XPath("//option"));
int DpListCount = AllDropDownList.Count;
for (int i = 0; i < DpListCount; i++)
{
if (AllDropDownList[i].Text == "Coffee")
{
AllDropDownList[i].Click();
}
}
Console.WriteLine(DpListCount);
Console.ReadLine();
}
}
}
您還可以使用:
new SelectElement(driver.FindElement(By.Id("")).SelectByText(""));
要么:
new SelectElement(driver.FindElement(By.Id("")).SelectByValue(""));
使用以下簡單的示例代碼:
String Input="Value to Select";
String xPathVal="@["id=Samplexpath"]";
IWebElement TargetElement = driver.FindElement(By.XPath(xPathVal));
SelectElement dropdown = new SelectElement(TargetElement);
dropdown.SelectByText(Input.Trim());
這很完美......
SelectElement selector = new SelectElement(element);
selector.SelectByIndex(1);
元素是你的下拉框。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.