Home >Web Front-end >CSS Tutorial >Why Does Selenium's `span:contains('string')` Selector Fail, and How Can I Fix It?
When attempting to find an element using CSS selector with span:contains('string') in Python Selenium for Firefox, you may encounter the error:
selenium.common.exceptions.InvalidSelectorException: Message: Given css selector expression "span:contains('string')" is invalid: InvalidSelectorError: 'span:contains('string')' is not a valid selector: "span:contains('string')"
This issue arises because the :contains pseudo-class is not supported by CSS specifications nor natively by Firefox or Chrome. It was exclusive to the Selenium 1.0 Sizzle Selector Engine, but WebDriver does not support such selectors.
Alternative Solutions:
Use attribute selectors:
element = "span[attribute_name=attribute_value]"
Use XPath, which supports text(), contains(), and normalize-space() methods:
element = my_driver.find_element_by_xpath("//span[text()='Control panel']")
Employ jQuery, which supports CSS selectors:
$('span:contains("Control panel")')
Trivia:
The above is the detailed content of Why Does Selenium's `span:contains('string')` Selector Fail, and How Can I Fix It?. For more information, please follow other related articles on the PHP Chinese website!