简体   繁体   中英

How to select a list item from a drop down by its value using Selenium Webdriver C#

I want to select a drop down value. The problem is the drop down list is derived, it is written as list items. Code snippet as follows:

<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>

How do I select 'Option 2' as the selected value in the drop down?

using CSS Selectors in Selenium:

you can get value of nth child by finding it with CSS Selector.

// 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)"));

In case of when <li> items are dynamic, then get count and loop over and get all the values.

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)"));
}

Finding element by Text (value)

Easier way would be finding by xPath and Class

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

for more -Example code

try (only if ul is treated as dropdown):

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

Reference:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM