"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Resolve InvalidSelectorException with \"span:contains(\'String\')\" in Selenium?

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

Published on 2024-11-06
Browse:895

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:

element = "span[attribute_name=attribute_value]"

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:

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

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.

Release Statement This article is reprinted at: 1729259896 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3