Reputation:
I am using chromedriver in CS to find an element using css selector however I receive the following error:
OpenQA.Selenium.InvalidSelectorException: 'invalid selector: An invalid or illegal selector was specified
My code:
var body = driver.FindElementsByCssSelector(".add-to-cart.float-right.font-montserratSemiBold.text-11.lg:text-12.text-secondary.flex.flex-wrap.leading-articlesmall");
I am trying to find the element of the Add to basket
buttons on this website
What is wrong with my selector and how can I resolve this issue?
Upvotes: 3
Views: 3870
Reputation: 193338
This error message...
OpenQA.Selenium.InvalidSelectorException: 'invalid selector: An invalid or illegal selector was specified
...implies that the WebDriver instance was unable to locate the desired WebElement was invalid.
The css-selectors was almost perfect but the issue was with :
as in lg:text-12
. The character :
have a special effect when used within a css-selectors as it is used in a couple of css-selectors variants. A few examples:
input:enabled
p:first-child
p:first-of-type
:not(p)
p:nth-child(2)
p:nth-last-of-type(2)
There are two solutions.
:
character.css-selectors:
button.add-to-cart
xpath
//button[contains(@class, 'add-to-cart')]
Snapshot:
You can find a couple of relevant detailed discussions in:
Upvotes: 3
Reputation: 978
You can use findelements method in selenium
List<WebElement> products=driver.findElements(By.xpath("//button[contains(text(),'Add to basket')]"));
// if you want to pick 1 st product you can use below code
products.get(0).click();
Upvotes: 0
Reputation: 1
Please try adding double backslashes escape character before : in lg:text-12 as shown below
var body = driver.FindElements(By.CssSelector(".add-to-cart.float-right.font-montserratSemiBold.text-11.lg\\:text-12.text-secondary.flex.flex-wrap.leading-articlesmall"));
Tested this in my local and worked fine returning eleven elements.
Upvotes: 0
Reputation: 7563
Try this selector:
var body = driver.FindElementsByCssSelector(".add-to-cart");
Upvotes: 0