user13939246
user13939246

Reputation:

OpenQA.Selenium.InvalidSelectorException: 'invalid selector: An invalid or illegal selector was specified error in Selenium

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

Answers (4)

undetected Selenium
undetected Selenium

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 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)

Solution

There are two solutions.

  • In the first approach you can escape the : character.
  • In the second and the most effective approach instead of mentioning all the class attributes, you can use a single static classname which identifies all the elements with text as Add to basket as follows:
    • css-selectors:

      button.add-to-cart
      
    • xpath

      //button[contains(@class, 'add-to-cart')]
      

Snapshot:

AddTobasket


References

You can find a couple of relevant detailed discussions in:

Upvotes: 3

Justin Lambert
Justin Lambert

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

Rap
Rap

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

frianH
frianH

Reputation: 7563

Try this selector:

var body = driver.FindElementsByCssSelector(".add-to-cart");

Upvotes: 0

Related Questions