由於ZloiAdun提到,有在OpenQA.Selenium.Support.UI命名空間中一個可愛的新選擇類。這是訪問選擇元素的最佳方式之一,因爲它的API非常簡單,所以它是選項。假設您的網頁看起來像這樣
<!DOCTYPE html>
<head>
<title>Disposable Page</title>
</head>
<body >
<select id="select">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
</body>
</html>
您正在訪問select的代碼看起來像這樣。請注意,我如何通過將正常的IWebElement傳遞給它的構造函數來創建Select對象。在Select對象上有很多方法。 Take a look at the source以獲取更多信息,直到獲得適當的文檔。
using OpenQA.Selenium.Support.UI;
using OpenQA.Selenium;
using System.Collections.Generic;
using OpenQA.Selenium.IE;
namespace Selenium2
{
class SelectExample
{
public static void Main(string[] args)
{
IWebDriver driver = new InternetExplorerDriver();
driver.Navigate().GoToUrl("www.example.com");
//note how here's i'm passing in a normal IWebElement to the Select
// constructor
Select select = new Select(driver.FindElement(By.Id("select")));
IList<IWebElement> options = select.GetOptions();
foreach (IWebElement option in options)
{
System.Console.WriteLine(option.Text);
}
select.SelectByValue("audi");
//This is only here so you have time to read the output and
System.Console.ReadLine();
driver.Quit();
}
}
}
然而,有幾點需要注意支持類。即使您下載了最新的測試版,支持DLL也不會在那裏。支持包在Java庫中有相對較長的歷史(這是PageObject所在的地方),但它在.Net驅動程序中仍然很新穎。幸運的是,從源代碼構建起來非常簡單。然後,I pulled from SVN從測試版下載中引用了WebDriver.Common.dll並構建在C#Express 2008中。此類尚未像其他一些類一樣經過測試,但我的示例在Internet Explorer和Firefox中工作。
根據上面的代碼,我應該指出一些其他的事情。首先行你使用查找選擇元素
driver.FindElements(By.TagName("select"));
是要找到所有選擇元素。你應該使用driver.FindElement
,沒有's'。
此外,您很少會直接使用INavigation。您將完成大部分導航,如driver.Navigate().GoToUrl("http://example.com");
最後,DefaultSelenium
是訪問較舊的Selenium 1.x apis的方式。 Selenium 2與Selenium 1相差甚遠,因此除非您嘗試將舊測試遷移到新的Selenium 2 api(通常稱爲WebDriver api),否則不會使用DefaultSelenium。
`IWebElement`沒有`SetSelected`方法。有一種叫做「Select」的方法,但對我而言,它沒有做任何事情。 – 2011-01-11 14:48:17
我不使用C#,所以我可能會錯過方法名稱 - 對不起。你有沒有嘗試過使用OpenQA.Selenium.Support.UI.Select類?你在選擇的選項上使用Select()嗎? – 2011-01-11 14:59:15