Selenium.common.exceptions.InvalidSelectorException with "span:contains('string')"
When using Selenium Python in Firefox and attempting to find an element using the CSS selector "span:contains('Control panel')", the following error is encountered:
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')"
In Selenium IDE, this method successfully locates the element. However, in Python, it fails.
Root Cause
As per the CSS specification, the ":contains" pseudo-class is not supported by Firefox or Chrome, even outside of WebDriver. It was specific to the Sizzle Selector Engine used in Selenium 1.0. However, WebDriver does not support Sizzle-style CSS selectors.
Solution
Instead of ":contains," use attributes or XPath selectors:
Attributes:
element = "span[attribute_name=attribute_value]"
XPath:
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']")
Alternative Solution
Use jQuery:
$('span:contains("Control panel")')
Trivia
The above is the detailed content of How to Handle InvalidSelectorException with \'span:contains(\'string\')\' in Selenium Python Firefox?. For more information, please follow other related articles on the PHP Chinese website!