Home  >  Article  >  Backend Development  >  How to Resolve InvalidSelectorException with \"span:contains(\'String\')\" in Selenium?

How to Resolve InvalidSelectorException with \"span:contains(\'String\')\" in Selenium?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-18 21:58:30512browse

How to Resolve InvalidSelectorException with

Invalid SelectorException in Selenium with "span:contains('String')"

When using Selenium in Python with Firefox, attempting to find an element using the CSS selector "span:contains('Control panel')" may result in the following error:

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

This error indicates that the provided CSS selector is invalid. According to Issue#987 and Issue#1547, the ":contains" pseudo-class is not supported by Firefox or Chrome.

Solution:

The ":contains" pseudo-class is not a standard CSS selector and should be replaced with an alternative attribute selector. For example:

<code class="python">element = "span[attribute_name=attribute_value]"</code>

Alternate XPaths:

If an attribute selector is not available, you can use one of the following XPaths:

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

jQuery Alternative:

<code class="javascript">$('span:contains("Control panel")')</code>

Note:

CSS selectors are not supported in the browser console, but JQuery provides a shortcut for document.querySelector. As such, JQuery may support CSS selectors if it is enabled on the page.

The above is the detailed content of How to Resolve InvalidSelectorException with \"span:contains(\'String\')\" in Selenium?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn