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.
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>
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']")
<code class="javascript">$('span:contains("Control panel")')</code>
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!