Home >Web Front-end >CSS Tutorial >Why Does 'span:contains('string')' Fail in Selenium with Firefox, and How Can I Fix It?
Invalid SelectorException Occurs with "span:contains('string')" in Selenium with Firefox
When attempting to locate an element by CSS selector in Selenium Python with Firefox, the "span:contains('Control panel')" expression may encounter an InvalidSelectorException with the message "Given CSS selector expression 'span:contains('Control panel')' is invalid."
As explained in GitHub issues #987 and #1547, the :contains pseudo-class is not supported in the CSS specification and is consequently not recognized by Firefox. This pseudo-class was part of the Sizzle selector engine used in Selenium 1.0, but WebDriver does not support Sizzle-style CSS selectors.
For browsers that do not natively support CSS selectors (such as IE7 and IE8), :contains may still function, leading to inconsistencies across different browsers. A more reliable approach would be to use another attribute of the span tag, such as:
element = "span[attribute_name=attribute_value]"
Alternative Solutions:
If the intended element is a span with the text "Control panel," you can use one of the following XPath expressions based on 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:
jQuery also supports the :contains pseudo-class, allowing you to use the following expression:
$('span:contains("Control panel")')
Additional Note:
Remember that CSS selectors are not natively supported by the browser console, but jQuery supports them via the $('...') shortcut, which usually overrides the default document.querySelector method.
The above is the detailed content of Why Does 'span:contains('string')' Fail in Selenium with Firefox, and How Can I Fix It?. For more information, please follow other related articles on the PHP Chinese website!