Home >Backend Development >Python Tutorial >How to Resolve InvalidSelectorException with \'span:contains(\'string\')\'

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

DDD
DDDOriginal
2024-10-18 22:02:03764browse

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]"

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']")
  • 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']")

jQuery Usage

Additionally, you can employ jQuery with the following syntax:

$('span:contains("Control panel")')

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!

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