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
Release: 2024-12-14 17:58:11
Original
601 people have browsed it

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]"
Copy after login

Alternatively, use XPath expressions:

  • Using "text()":
element = my_driver.find_element_by_xpath("//span[text()='Control panel']")
Copy after login
  • Using "contains()":
element = my_driver.find_element_by_xpath("//span[contains(.,'Control panel')]")
Copy after login
  • Using "normalize-space()":
element = my_driver.find_element_by_xpath("//span[normalize-space()='Control panel']")
Copy after login

Using jQuery

jQuery provides a workaround:

$('span:contains("Control panel")')
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template