3

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?

undetected Selenium
  • 183,867
  • 41
  • 278
  • 352
  • Please check that your page doesn't have iFrame elements first. If it has, you should switch to the needed frame before 'findEelement' – Sergii Dmytrenko Jul 17 '20 at 06:46

2 Answers2

3

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:

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

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

Justin Lambert
  • 940
  • 1
  • 7
  • 13