2014-08-28 35 views
0

我使用Selenuim webdriver的,我需要點擊兩個下拉菜單一個個寫在C#自動化測試腳本創建下拉列表。下面是兩個下拉元素的HTML源代碼:無法找到由jQuery插件

<select id="ServiceTypeId" class="chosen chzn-done" tabindex="-1" name="ServiceTypeId" style="display: none;"></select> 
    <div id="ServiceTypeId_chzn" class="chzn-container chzn-container-single"> 
     <a class="chzn-single" tabindex="-1" href="javascript:void(0)"><span>Choose an Option</span></a> 
     <div class="chzn-drop"></div> 
    </div> 
    </div> 
<select id="PropertyTypeId" class="chosen chzn-done" tabindex="-1" name="PropertyTypeId" style="display: none;"></select> 
    <div id="PropertyTypeId_chzn" class="chzn-container chzn-container-single"> 
     <a class="chzn-single" tabindex="-1" href="javascript:void(0)"></a> 
     <div class="chzn-drop"></div> 
    </div> 

我能夠通過CssSelector成功定位在第一個下拉列表(ServiceTypeId)的元素是這樣的:

driver.FindElement(By.CssSelector("div.chzn-container a.chzn-single")).Click(); 
Thread.Sleep(1000); 
driver.FindElements(By.CssSelector("div.chzn-drop li.active-result"))[5].Click(); 
Thread.Sleep(500); 

不過,我不能找到第二個下拉列表(PropertyTypeId),因爲它們都應用了相同的類。

我試着用用自己的ID,但它不工作找到他們:

driver.FindElement(By.Id("PropertyTypeId_chzn")).Click(); 

我覺得這個插件已經被用來創建dowpdowns:jQuery plugin

能有人幫我想個辦法去做這個?

編輯:
的兩個元素被設置爲display:none,因此當我試圖點擊它們使用driver.FindElement(By.Id("ServiceTypeId")).Click();我收到錯誤:

Element is not currently visible and so may not be interacted with

回答

0

我找到了解決這個,想分享它,因爲它可以幫助別人面臨着類似的問題。
主要問題是元素被設置爲display:none,所以在點擊它們之前,它們應該是可見的。我可以使用JavaScript這樣做:

IJavaScriptExecutor js = driver as IJavaScriptExecutor; 

js.ExecuteScript("document.getElementById('ServiceTypeId').style.display = '';"); 
Thread.Sleep(500); 

driver.FindElement(By.Id("ServiceTypeId")).Click(); 
Thread.Sleep(300); 

js.ExecuteScript("document.getElementById('PropertyTypeId').style.display = '';"); 
Thread.Sleep(2000); 

driver.FindElement(By.Id("PropertyTypeId")).Click(); 
Thread.Sleep(500); 

謝謝。

0

嘗試CSS3 pseudoselector

driver.FindElement(By.CssSelector("select:nth-of-type(1)")).Click(); 
0

如何創建這些下拉並不重要,我認爲選擇器的問題。順便說一句,如果將來你想從dropDowns中選擇值,不要忘記先點擊dropDown,然後從中選擇值。無論如何,接下來的代碼應工作:

driver.FindElement(By.CssSelector("#ServiceTypeId")); 
driver.FindElement(By.CssSelector("#PropertyTypeId")); 

UPDATE

//Click on first a link then li will appear in div. Click on 6th elem 
driver.findElement(By.CssSelector("#ServiceTypeId_chzn > a")).click(); 
driver.findElements(By.CssSelector("#ServiceTypeId_chzn .chzn-drop > li"))[5].click(); 
//Same for second 
driver.findElement(By.CssSelector("#PropertyTypeId_chzn > a")).click(); 
driver.findElements(By.CssSelector("#PropertyTypeId_chzn .chzn-drop > li"))[5].click(); 
+0

我編輯並添加了一些更多的信息給我的問題。重點是ServiceTypeId和PropertyTypeId被設置爲顯示:none – Luftwaffe 2014-08-30 12:52:55

+0

那麼,但你可以找到第一個元素,即使它是display == none。可能我在選擇器中犯了一個錯誤(很難猜到完全的html結構和行爲,點擊後你無法看到它)。讓我們再試一次。請嘗試下一個選擇器,讓我知道他們是否工作。)。 – 2014-08-30 13:59:18

+0

答案已經更新,請看看它。希望這會幫助你。 – 2014-08-30 14:05:03