user6507067
user6507067

Reputation: 13

Selenium Web driver - unable to locate element

I am new to Selenium-WebDriver. Trying to locate an element and click on it.

But constantly getting below error:

unable to locate an element

Firepath provided following xpath:

"xpath = html/body/header/div/ul/li[2]/a/span[1]"

The relevant HTML code is:

<ul class="nav navbar-nav navbar-right top-nav ">
<li class="identity has-icon">
<a href=".......">
</li>
<li class="settings has-icon">
<a href=".......">
<span class="icon icon-cogs" aria-hidden="true" role="presentation"/>
**<span class="nav-title">Settings</span>**
</a>
</li>

I have tried to find the element in following ways:

1. driver.findElement(By.xpath("//div[@id='right-nav']//a[contains(text(),'Settings')]")).click();

2.  driver.findElement(By.xpath("//div[@id='nav-title']//a[contains(text(),'Settings')]")).click();

3. driver.findElement(By.xpath("//div[contains(@class, 'nav-title')]")).click();

Could someone help me find a solution?

Upvotes: 1

Views: 2322

Answers (6)

JeffC
JeffC

Reputation: 25744

This simple CSS selector might work. It's hard to tell if it's unique enough without more of the HTML of the page. It's looking for a SPAN tag with the class nav-title.

driver.findElement(By.cssSelector("span.nav-title")).click();

Upvotes: 0

Amol Chavan
Amol Chavan

Reputation: 3990

You are almost there, In last xpath you have used div, instead of that try using span.

"//span[contains(@class, 'nav-title')]"

Upvotes: 1

Ravi Potnuru
Ravi Potnuru

Reputation: 191

Try any of the below. you will get the element

//span[@class='icon icon-cogs']
//span[@class='icon icon-cogs'][@role='presentation']
//span[@class='icon icon-cogs'][@role='presentation']/span

Hope it will help you

Upvotes: 0

Sudharsan Selvaraj
Sudharsan Selvaraj

Reputation: 4832

You need to click on the span element with text "Settings". so the below xpath will search for a span element which contains Settings as text inside any anchor tag.

.//a/descendant::*[contains(text(),'Settings')]

Upvotes: 0

Pankaj Kumar
Pankaj Kumar

Reputation: 61

You need to click on "a (link)" tag directly because inner tags are acting as css only (page looks to be using bootstrap). Try following code, it should work

driver.findElement(By.xpath("//a[contains(@href,'PUT href texts here')]")).click()

If this is not working , please mention browser and selenium version in the comment.

Upvotes: 0

Rao
Rao

Reputation: 21389

It does not require a contains there and that too all of your statement contains // twice in xpath which is incorrect.

Please use the below statement

//@ is used to get the span class which is nav-title and 
// whose span text is Settings
driver.findElement(By.xpath("//li/a/span[@class ='nav-title' and . = 'Settings']")).click();

Upvotes: 0

Related Questions