Error: "Selenium.common.exceptions.InvalidSelectorException" with "span:contains('string')" in Selenium Python Firefox
When trying to locate an element using CSS selectors with the "contains" function, such as "span:contains('Control panel')", you may encounter the following error:
selenium.common.exceptions.InvalidSelectorException: Message: Given css selector expression "span:contains('Control panel')" is invalid: InvalidSelectorError: 'span:contains('Control panel')' is not a valid selector: "span:contains('Control panel')"
Explanation:
This error occurs because the ":contains" pseudo-class is not supported in native CSS selectors by Firefox or Chrome. It was previously used in the Sizzle Selector Engine that Selenium 1.0 relied on, but was dropped in WebDriver due to inconsistencies across browsers.
Solution 1: Use Other CSS Attributes
Instead of using the ":contains" pseudo-class, search for the element using a different CSS attribute, such as class, id, or other identifying properties. For example:
element = "span[attribute_name=attribute_value]"
Solution 2: Use XPath
XPath supports the ":contains" pseudo-class, so you can use it to locate the element:
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']")
Solution 3: Use jQuery
Alternatively, you can use jQuery to locate the element with the "contains" function:
$('span:contains("Control panel")')
The above is the detailed content of How to Handle \'Selenium.common.exceptions.InvalidSelectorException\' with \'span:contains(\'string\')\' in Selenium Python Firefox?. For more information, please follow other related articles on the PHP Chinese website!