2011-01-11 38 views
5

我使用Selenium的IWebDriver在C#中編寫單元測試。使用Selenium 2的IWebDriver與頁面上的元素進行交互

這樣是一個例子:

IWebDriver defaultDriver = new InternetExplorerDriver(); 
var ddl = driver.FindElements(By.TagName("select")); 

最後一行檢索包裹在一個IWebElementselect HTML元素。

需要一種方法來模擬選擇一個特定的optionselect名單,但我無法弄清楚如何做到這一點。


在一些research,我發現那裏的人都使用ISelenium DefaultSelenium類來完成以下的例子,但因爲我所做的一切與IWebDriverINavigation(從defaultDriver.Navigate())我不會使這個類的使用。

我也注意到ISelenium DefaultSelenium包含了很多其他的方法,在IWebDriver的具體實現中不可用。

那麼有沒有什麼辦法可以使用IWebDriverINavigation配合ISelenium DefaultSelenium

回答

7

由於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。

2

您應該從select使用ddl.FindElements(By.TagName("option"));獲取所有option元素。然後你就可以通過返回的集合迭代,並通過使用IWebElement

更新SetSelected方法選擇所需項目(S):看來,現在有在的webdriver的Select的C#實現 - 以前是在Java中只。請看看它的code和更容易使用這個類

+0

`IWebElement`沒有`SetSelected`方法。有一種叫做「Select」的方法,但對我而言,它沒有做任何事情。 – 2011-01-11 14:48:17

+0

我不使用C#,所以我可能會錯過方法名稱 - 對不起。你有沒有嘗試過使用OpenQA.Selenium.Support.UI.Select類?你在選擇的選項上使用Select()嗎? – 2011-01-11 14:59:15

相關問題