Reputation: 102
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
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 xpath based Locator Strategy:
driver.findElement(By.xpath("//button[@class='signup-button' and text()='Get Started!']")).click();
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();
You can find a couple of relevant discussions in:
Upvotes: 3
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