Lakshan Chathuranga
Lakshan Chathuranga

Reputation: 102

Unable to locate element using className in Selenium and Java

I wanted to locate a element of a web page using class name in Selenium. This is the web element that I tried:

<button class="signup-button b green">Get Started!</button>

When I try this way, I was unable to locate the button;

driver.findElement(By.className("signup-button")).click();

But, using css selector like below, it was working;

driver.findElement(By.cssSelector("button.signup-button")).click();

What is the reason for that sometimes working and other times not working?

Upvotes: 3

Views: 1677

Answers (2)

undetected Selenium
undetected Selenium

Reputation: 193068

As you are able to locate the following element:

<button class="signup-button b green">Get Started!</button>

using:

driver.findElement(By.cssSelector("button.signup-button")).click();

but was unable to locate the same element using:

driver.findElement(By.className("signup-button")).click();

That's because there were other elements which renders within the HTML DOM with className as signup-button even before the desired element, which possibly may be invisible by design.

Ideally, you should also be able to use a based Locator Strategy:

driver.findElement(By.xpath("//button[@class='signup-button' and text()='Get Started!']")).click();

Best Practices

But as per best practices, you need to use WebDriverWait for the elementToBeClickable() and you can use either of the following Locator Strategies:

  • cssSelector:

    new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.cssSelector("button.signup-button"))).click();
    
  • xpath:

    new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//button[@class='signup-button' and text()='Get Started!']"))).click();
    

References

You can find a couple of relevant discussions in:

Upvotes: 3

Justin Lambert
Justin Lambert

Reputation: 978

You need to use relative xpath , if you could not have locators like id and class name Can you try with //button[contains(text(),"Get Started!")] this xpath

Upvotes: 1

Related Questions