简体   繁体   中英

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

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

You are getting the error because your CSS selector is incorrect. You have listed the class names but classes should be preceeded with a . , eg .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.

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