3

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?

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

4 Answers4

2

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:

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

Try this selector:

var body = driver.FindElementsByCssSelector(".add-to-cart");
frianH
  • 7,295
  • 6
  • 20
  • 45
0

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.

Rap
  • 1
  • 2
0
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();
Justin Lambert
  • 940
  • 1
  • 7
  • 13