Search code examples
javaseleniumxpathcss-selectorslinktext

How to click a button in an automated test using Selenium and Java


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


Solution

  • 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: