Home >Web Front-end >CSS Tutorial >Why Does Selenium Throw an InvalidSelectorException with 'span:contains('Control panel')'?

Why Does Selenium Throw an InvalidSelectorException with 'span:contains('Control panel')'?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-14 17:58:11605browse

Why Does Selenium Throw an InvalidSelectorException with

Selenium InvalidSelectorException with "span:contains('Control panel')"

Attempting to find an element using the CSS selector "span:contains('Control panel')" in Selenium Python may result in an InvalidSelectorException. This error occurs because the "contains" pseudo-class is not recognized by Firefox or Chrome.

The CSS specification does not include the ":contains" pseudo-class. As such, it is unsupported by browsers that adhere to the standard. Additionally, WebDriver does not support the "Sizzle" selector engine, which allowed for the use of ":contains" in Selenium 1.0.

Alternative Solutions

Instead of ":contains", consider using attributes of the tag to identify the element:

element = "span[attribute_name=attribute_value]"

Alternatively, use XPath expressions:

  • 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 provides a workaround:

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

The above is the detailed content of Why Does Selenium Throw an InvalidSelectorException with 'span:contains('Control panel')'?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn