Home  >  Article  >  Backend Development  >  How to Handle InvalidSelectorException with \"span:contains(\'string\')\" in Selenium Python Firefox?

How to Handle InvalidSelectorException with \"span:contains(\'string\')\" in Selenium Python Firefox?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-18 21:59:03510browse

How to Handle InvalidSelectorException with

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

  • CSS selectors are not supported by the console either, but jQuery supports them through $('...'), which overrides document.querySelector when jQuery is present on the page.

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!

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