Home >Backend Development >Python Tutorial >How to Resolve InvalidSelectorException with \'span:contains(\'string\')\'
When attempting to locate an element with the CSS selector "span:contains('Control panel')", an InvalidSelectorException is encountered, displaying the error: "Given css selector expression "span:contains('Control panel')" is invalid".
As explained in Issue #987 and #1547, the :contains pseudo-class is not included in the CSS specification and lacks support in both Firefox and Chrome. This pseudo-class was unique to the Sizzle Selector Engine used by Selenium 1.0. However, WebDriver opted against incorporating Sizzle's CSS selectors, resulting in this inconsistency.
To resolve this issue effectively, employ alternative attributes of the tag:
element = "span[attribute_name=attribute_value]"
For locating the element using the provided DOM Tree, consider the following XPath options:
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']")
Additionally, you can employ jQuery with the following syntax:
$('span:contains("Control panel")')
As per @FlorentB's insight, CSS selectors are not supported by the console, yet jQuery provides support. The '$(...)' syntax within the console represents a shorthand notation for 'document.querySelector', which becomes overridden by jQuery upon its inclusion in the page.
The above is the detailed content of How to Resolve InvalidSelectorException with \'span:contains(\'string\')\'. For more information, please follow other related articles on the PHP Chinese website!