2016-11-08 200 views
1

我想選擇一個下拉值。問題是派生的下拉列表,它被寫爲列表項。代碼片段如下:如何使用Selenium Webdriver從下拉列表中選擇一個列表項目的值C#

<div class="rcbScroll" style="width: 100%; height: 184px; overflow: auto;"> 
<ul class="rcbList" style="width: 100%"> 
    <li class="rcbItem">Option 1</li> 
    <li class="rcbItem">Option 2</li> 
    <li class="rcbItem">Option 3</li> 
</ul> 

如何在下拉菜單中選擇「選項2」作爲選定值?硒

+0

這是一個'ul'風格看起來像一個下拉列表?還是你的意思是使用一個實際的'select'元素? –

+0

這是一個'ul'元素,看起來像一個下拉式。 – Annie

回答

1

使用CSS選擇器:

您可以通過CSS選擇器發現它獲得第n個孩子的價值。

// first child: will return "Option 1" 
driver.findElement(By.cssSelector("ul.rcbList > li:nth-child(1)")); 

// second child: will return "Option 2" 
driver.findElement(By.cssSelector("ul.rcbList > li:nth-child(2)")); 

// nth child: will return "Option n" 
driver.findElement(By.cssSelector("ul.rcbList > li:nth-child(n)")); 

在當<li>項目是動態的情況下,然後得到計數和遍歷並獲得所有的值。

var el_count = driver.FindElements(By.CssSelector("ul.rcbList")); 

for(int index=0; index < el_count.count(); index++){ 
    // 0 (zero) is the first element in <ul> DOM Array 
    driver.findElement(By.cssSelector("ul > li:nth-child(index)")); 
} 

通過查找文本元素(值)

更簡單的方法就是通過XPath和類

var title = driver.FindElement(By.XPath("./div[@class='aCont']/div/a/span[text() = 'TextToFind']")); 
// now title contains text, title = "text to be find" 

更多-Example code

+0

謝謝。第一種選擇對我來說已經足夠了。 – Annie

+0

略有變化。 driver.FindElement(By.CssSelector(「ul.rcbList> li:nth-​​child(1)」))。Click(); (我必須指定'ul'element的類名稱) – Annie

+0

有沒有一種語法可以按照它的值來選擇列表項?沿列表項目包含「選項2」的東西 – Annie

0

嘗試被發現(只有ul被處理作爲下拉):

SelectElement selectElement = new SelectElement(driver.FindElement(By.cssSelector(".rcbList"))); 
selectElement.SelectByText("Option 2"); 

參考:

https://stackoverflow.com/a/31072586/2575259

+0

對不起。沒有適用於這種情況。 'SelectElement'只能用於選擇HTML元素,而不能用於無序列表項。 – Annie

相關問題