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:


    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:


    Reference

    You can find a couple of relevant discussions in: