1

I'm trying to automate a test using Selenium and I want to click a button using xpath. This is what I'm doing:

WebElement LogInButton = driver.findElement(By.xpath("/login"));
LogInButton.click();

But I get an error that says:

Exception in thread "main" org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"xpath","selector":"/login"}

The only information I have about that button is this:

<a href="/login">Login</a>

and the URL where it redirects to. What am I doing wrong? What would be the correct way of referring to this button? Any help please let me know. Thanks

undetected Selenium
  • 183,867
  • 41
  • 278
  • 352
iag20
  • 73
  • 1
  • 4
  • 1
    your xpath is looking for a tag "". You want to specify text or href. Try with By.linkText("Login") – pcalkins Jun 02 '20 at 20:50

1 Answers1

0

To invoke click() on the element you can use either of the following Locator Strategies:

  • Using linkText:

    driver.findElement(By.linkText("Login")).click();
    
  • Using cssSelector:

    driver.findElement(By.cssSelector("a[href='/login']")).click();
    
  • Using xpath:

    driver.findElement(By.xpath("//a[@href='/login' and text()='Login']")).click();
    

Best practices

As you are invoking click() ideally you need to induce WebDriverWait for the elementToBeClickable() and you can use either of the following Locator Strategies:

  • Using linkText:

    new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.linkText("Login"))).click();
    
  • Using cssSelector:

    new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.cssSelector("a[href='/login']"))).click();
    
  • Using xpath:

    new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//a[@href='/login' and text()='Login']"))).click();
    

Reference

You can find a couple of relevant discussions in:

undetected Selenium
  • 183,867
  • 41
  • 278
  • 352