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

Mary-Kate Olsen
Release: 2024-10-18 21:59:03
Original
522 people have browsed it

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

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

    • 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

Alternative Solution

Use jQuery:

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

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!

source:php
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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!