How to Resolve InvalidSelectorException with \'span:contains(\'string\')\'

DDD
Release: 2024-10-18 22:02:03
Original
662 people have browsed it

How to Resolve InvalidSelectorException with

InvalidSelectorException with "span:contains('string')"

When attempting to locate an element with the CSS selector "span:contains('Control panel')", an InvalidSelectorException is encountered, displaying the error: "Given css selector expression "span:contains('Control panel')" is invalid".

As explained in Issue #987 and #1547, the :contains pseudo-class is not included in the CSS specification and lacks support in both Firefox and Chrome. This pseudo-class was unique to the Sizzle Selector Engine used by Selenium 1.0. However, WebDriver opted against incorporating Sizzle's CSS selectors, resulting in this inconsistency.

To resolve this issue effectively, employ alternative attributes of the tag:

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

Alternative Solutions

For locating the element using the provided DOM Tree, consider the following XPath options:

  • 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

jQuery Usage

Additionally, you can employ jQuery with the following syntax:

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

Noteworthy Observation

As per @FlorentB's insight, CSS selectors are not supported by the console, yet jQuery provides support. The '$(...)' syntax within the console represents a shorthand notation for 'document.querySelector', which becomes overridden by jQuery upon its inclusion in the page.

The above is the detailed content of How to Resolve InvalidSelectorException with \'span:contains(\'string\')\'. 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
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!