Zoran
Zoran

Reputation: 499

Find 'li' element

Could someone please assist me in order to find 5th 'li' element since that receiving error when trying to locate it. Following is how looks on page:

<ul class="navigation-primary navigation-primary--right js-navigation-primary">
<li><a data-modal="login-modal" href="javascript:void(0);" data-modal-content-switch="login-options" class="is-button-group-right js-prevent-trigger modal-content-button"><span>Logga in</span></a></li>
<li><a href="javascript:void(0)" class="icon icons8-Search has-no-border-bottom" data-menu="search"></a></li>
<li><a href="javascript:void(0)" class="has-no-border-bottom" data-menu="language">Svenska</a></li>

Actually, I need last one with following attribute

data-menu="language"

Since there are several languages - I suppose that it would solve with if loop:

if (driver.findElement(By.xpath("//*[@id="header"]/div[2]/div/ul[2]/li[5]/a") != null
driver.findElement(By.xpath("//*[@id="header"]/div[2]/div/ul[2]/li[5]/a").click();
else {
 system.out.println("element not present");

 }

Since that there are several languages and every has last li[5] - thought that lang name could solve it, but did not find solution. Thank you in advance

Upvotes: 1

Views: 682

Answers (3)

JeffC
JeffC

Reputation: 25744

I know you accepted an answer but it would be a lot cleaner and clearer if you used a simple CSS selector like

driver.findElement(By.cssSelector("a[data-menu='language']")).click();

or you could be more specific and find the element by language using XPath

driver.findElement(By.xpath("//a[@data-menu='language'][.='Svenska']")).click();

Also, you can't check if an element is null. If it's not there, .findElement() will just throw an exception. If you want to check if an elements exists, use .findElements() and check to see if the collection is empty

List<WebElement> links = driver.findElements(...);
if (links.isEmpty())
{
    // element doesn't exist
}
else
{
    // element exists
    links[0].click(); // or whatever
}

Upvotes: 2

Stormcloud
Stormcloud

Reputation: 2307

At the risk of redefining your question, I'd be tempted to add some id tags into your html and call driver.findElement(By.id(name)).

The advantage is that if an extra item is added to the start of list then your tests will not break.

Upvotes: -1

undetected Selenium
undetected Selenium

Reputation: 193348

As per the HTML you provided the following xpath/cssSelectorshould work:

driver.findElement(By.xpath("//ul[@class='navigation-primary navigation-primary--right js-navigation-primary']/li[contains(.,'Svenska')]"));

OR

driver.findElement(By.cssSelector("ul.navigation-primary.navigation-primary--right.js-navigation-primary > li.navigation-primary.navigation-primary--right.js-navigation-primary"));

Upvotes: 1

Related Questions