Shams
Shams

Reputation: 61

How to click in nav-bar and choose item from a list in selenium java

I have tried this

List <WebElement> navlist = driver.findElements(By.cssSelector("d-md-down-none nav navbar-nav mr-auto"));
navlist.get(0).findElement(By.linkText("Sources")).click();

Below is the HTML code:

<ul class="d-md-down-none nav navbar-nav mr-auto">
    <li class="px-3 nav-item">
        <a aria-disabled="false" href="#/sources" class="nav-link">Sources</a>
    </li>
    <li class="px-3 nav-item">
        <a aria-disabled="false" href="#/alerts" class="nav-link">Alerts</a>
    </li>
</ul>

Error when trying my example :

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 0, Size: 0 at java.util.ArrayList.rangeCheck(Unknown Source) at java.util.ArrayList.get(Unknown Source) at Adding_new_source.New_source.main(New_source.java:53) 

How to click in nav-bar and choose item from a list in selenium java

Upvotes: 1

Views: 2212

Answers (2)

JeffC
JeffC

Reputation: 25611

You are getting the error because your CSS selector is incorrect. You have listed the class names but classes should be preceeded with a ., e.g. .className. The equivalent of your code would be

List <WebElement> navlist = driver.findElements(By.cssSelector(".d-md-down-none.nav.navbar-nav.mr-auto"));
navlist.get(0).findElement(By.linkText("Sources")).click();

Have you tried the simpler

driver.findElement(By.linkText("Sources")).click();

It may or may not work depending on how many other "Sources" links there are on the page and where they are.

Upvotes: 0

undetected Selenium
undetected Selenium

Reputation: 193108

As per the HTML you have provided and your code trials you can choose and click an item with text as Sources from the List using the following code block :

List <WebElement> navlist = driver.findElements(By.cssSelector("ul.d-md-down-none.nav.navbar-nav.mr-auto li>a"));
for(WebElement elem:navlist)
    if(elem.getAttribute("innerHTML").contains("Sources"))
        {
            elem.click();
            break;
        }

Upvotes: 1

Related Questions