Locators has 4 matching nodes, how to write xpath in Selenium when we have 4 elements matching?

Viewed 357

My code in Selenium: driver.findElement(By.xpath("//a[@href='/agent-create-profile'][1]")).click();

It gives error: Exception in thread "main" org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"xpath","selector":"//a[@href='/agent-create-profile'][1]"}

Selectors hub shows 4 matching elements with the provided xpath:


<a tabindex="0" class="primary-button__PrimaryButton-iSIsNJ cjTSCX abstract-button abstract-button--size-large" href="/agent-create-profile" style="" xpath="2"> Create Profile </a>

<a tabindex="0" class="primary-button__PrimaryButton-iSIsNJ cjTSCX abstract-button abstract-button--size-large" href="/agent-create-profile" style="" xpath="3"> Let's start </a>

<a tabindex="0" class="primary-button__PrimaryButton-iSIsNJ cjTSCX abstract-button abstract-button--size-large" href="/agent-create-profile" style="" xpath="4"> Agent Sign up </a>

<a rel="noopener noreferrer" class="navigation-section__menu-link" href="/agent-create-profile" style="" xpath="4"></a>````


Below is the html code:
````<a tabindex="0" class="primary-button__PrimaryButton-iSIsNJ cjTSCX abstract-button abstract-button--size-large" href="/agent-create-profile" style="" xpath="1">Sign up</a>````
3 Answers

I think you are missing a set of parentheses, at the start of your xpath and before you hit [1]

Try this:

driver.findElement(By.xpath("(//a[@href='/agent-create-profile'])[1]")).click()

Another alternative if you want the first element:

driver.findElement(By.xpath("//a[contains(text(),'Create Profile')]")).click()

As xpath attributes are unique: there is one more option for xpath additionally to the existing answer:

driver.findElement(By.xpath("//a[@xpath='1']"));

And css is very similar:

driver.findElement(By.cssSelector("a[xpath='1']"));

Please try with the method- partialLinkText:

 driver.findElement(By.partialLinkText("Create Profile")).click();

Or you can select all links as list and iterate through for loop and match with the required link text fetching by getText() method. IF possible please share the website link.

List<WebElement> linkList = driver.findElements(By.xpath(“”));
for(WebElement link : linkList) {
   if (link.getText().contains(“create-profile”)) {
   link.click();
   break;
   }
}
Related