user2325154 user2325154 - 24 days ago 10
HTML Question

How to click an element in xpath and selenium having option-id element but same div class?

I have the following html code snippet.

<div class="swatch-attribute-options clearfix">
<div class="swatch-option color" option-type="1" option-id="49" option-label="Black" option-tooltip-value="#000000" "="" style="background: #000000 no-repeat center;"></div>
<div class="swatch-option color" option-type="1" option-id="52" option-label="Gray" option-tooltip-value="#8f8f8f" "="" style="background: #8f8f8f no-repeat center;"></div>
<div class="swatch-option color" option-type="1" option-id="57" option-label="Purple" option-tooltip-value="#ef3dff" "="" style="background: #ef3dff no-repeat center;"></div>
</div>


I want to click the first option (
option-id="49" option-label="Black"
) through
Selenium
and
Java
but not sure how to do that. This is what I tried and I got following exception.

driver.findElement(By.className("swatch-option color"));


Exception:

org.openqa.selenium.InvalidSelectorException: invalid selector: Compound class names not permitted.
*** Element info: {Using=class name, value=swatch-option color}
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:206)
at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:158)
at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:678)
at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:363)
at org.openqa.selenium.remote.RemoteWebDriver.findElementByClassName(RemoteWebDriver.java:477)
at org.openqa.selenium.By$ByClassName.findElement(By.java:391)
at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:355)
at com.radial.webstore.CheckoutFlowFunctionalTest.testCheckoutScenario(CheckoutFlowFunctionalTest.java:33)


Results :

Tests in error:
CheckoutFlowFunctionalTest.testCheckoutScenario:33 ยป InvalidSelector invalid s...

Answer

You can use css selectors like:

driver.findElement(By.cssSelector(".swatch-option.color")).click();

Or xpath:

driver.findElement(By.xpath("//div[@class='swatch-option color']")).click();

Of course you could get selectors based on other attributes, here are some examples with css:

.swatch-option.color[option-id=49]

.swatch-option.color[option-label=Black]
Comments