selenium.common.exceptions.InvalidSelectorException with "span:contains('string')"

I am working on selenium python in firefox. I am trying to find element by css selector

element = "span:contains('Control panel')"
my_driver.find_element_by_css_selector(element)

I am getting below error

 raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.InvalidSelectorException: Message: Given css selector expression "span:contains('Control panel')" is invalid: InvalidSelectorError: 'span:contains('Control panel')' is not a valid selector: "span:contains('Control panel')"

In selenium IDE I am successfully able to find element by this field but in Python it is not working


The error says it all :

selenium.common.exceptions.InvalidSelectorException: Message: Given css selector expression "span:contains('Control panel')" is invalid: InvalidSelectorError: 'span:contains('Control panel')' is not a valid selector: "span:contains('Control panel')"

As per Issue#987 and Issue#1547:

The :contains pseudo-class isn't in the CSS Spec and is not supported by either Firefox or Chrome (even outside WebDriver).

The pseudo-class was specific to the Sizzle Selector Engine that Selenium 1.0 relied on. But, it was decided that WebDriver was not going to support the Sizzle style CSS selectors that Selenium 1.0 used.

Now, an interesting fact is the :contains pseudo-class will work for browsers that don't natively support CSS selectors (IE7, IE8, etc) which causes inconsistencies between browsers and selectors.

Hence a better solution would have been to go with any other attribute of the <span> tag as follows :

element = "span[attribute_name=attribute_value]"

Alternate Solution

You can use either of the following xpaths as per the prevailing DOM Tree:

  • Using text():

    element = my_driver.find_element_by_xpath("//span[text()='Control panel']")
    
  • Using contains():

    element = my_driver.find_element_by_xpath("//span[contains(.,'Control panel')]")
    
  • Using normalize-space():

    element = my_driver.find_element_by_xpath("//span[normalize-space()='Control panel']")
    

Using jQuery

You can also use jQuery as follows:

$('span:contains("Control panel")')

Trivia :

A valuable comment from @FlorentB.

CSS selector is not supported by the console either, but JQuery supports it. The $('...') from the console is a shorthand for document.querySelector which is generally overridden with JQuery when the page has it.


Using css_selector to locate element by text is not supported in Selenium (although it will work in the developer tools console). The only possibility is xpath

element = "//span[contains(text(), 'Control panel')]"
my_driver.find_element_by_xpath(element)

Edit: a comment by @FlorentB:

A css selector is not supported by the console either, but JQuery supports it. The $('...') from the console is a shorthand for document.querySelector which is generally overridden with JQuery when the page has it.