Why Does CSS Selector with :contains() Cause \'InvalidSelectorException\' in Selenium Python with Firefox?

Patricia Arquette
Release: 2024-10-18 21:57:03
Original
139 people have browsed it

Why Does CSS Selector with :contains() Cause

Invalid CSS Selector in Selenium Python: "selenium.common.exceptions.InvalidSelectorException with "span:contains('string')""

When using Selenium Python with Firefox, attempting to find an element by CSS selector with the :contains() pseudo-class, such as "span:contains('Control panel')", may result in an "InvalidSelectorException."

Reason:

The :contains() pseudo-class is not supported by Firefox or Chrome. As noted in Issue #987 and #1547, WebDriver opted not to include support for Sizzle-style CSS selectors, which included :contains().

Alternative Solutions:

Instead, consider using any other attribute of the span tag, such as:

element = "span[attribute_name=attribute_value]"
Copy after login

Alternatively, use XPaths based on the DOM tree structure:

  • 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

Or, you can leverage jQuery for CSS selectors with :contains():

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

Note: CSS selectors with :contains() are also not supported in the console, but jQuery overwrites document.querySelector with its own implementation, allowing for their use.

The above is the detailed content of Why Does CSS Selector with :contains() Cause \'InvalidSelectorException\' in Selenium Python with 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!