Search code examples
c#seleniumxpathcss-selectorsinvalidselectorexception

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?


Solution

  • 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: