-1

My element is displayed as:

<a class="main-item" href="#">Business Loans</a>

xpath is:

//*[@id='main-nav']/ul/li[1]/a[1]']

This returns invalid element locator

//*[@id='main-nav']/ul/li[1]/a']

driver.findElement(By.xpath("//*[@id='main-nav']/ul/li[1]/a[1]']"))

I am trying to get the element.

undetected Selenium
  • 151,581
  • 34
  • 225
  • 281
ravi
  • 1
  • 1
  • 3

3 Answers3

0

Welcome to SO. Here is the simple xpath.

//*[@id='main-nav]//a[@class='main-item' and .='Business Loans']

If you want to use the one which you mentioned, here is the corrected.

driver.findElement(By.xpath("//*[@id='main-nav']/ul/li[1]/a[1]"))
supputuri
  • 13,136
  • 2
  • 18
  • 38
0

Try contains function in xpath, it can extract all the elements which matches a particular text value

//a[contains(text(),'Business Loans')]
Sandeep K
  • 56
  • 3
0

This error message...

org.openqa.selenium.InvalidSelectorException: invalid selector

...implies that your xpath was not a valid one.

You can't use the single quote i.e. ' or the double quote i.e. " for both By value and attribute values.


Solution

You can use either of the following Locator Strategies:

  • cssSelector:

    WebElement element = driver.findElement(By.cssSelector("#main-nav a.main-item"));
    
  • xpath:

    WebElement element = driver.findElement(By.xpath("//a[@class='main-item' and text()='Business Loans']"));
    
undetected Selenium
  • 151,581
  • 34
  • 225
  • 281