Home > Web Front-end > CSS Tutorial > Why Does Selenium's `span:contains('string')` Selector Fail, and How Can I Fix It?

Why Does Selenium's `span:contains('string')` Selector Fail, and How Can I Fix It?

Patricia Arquette
Release: 2024-12-13 13:44:10
Original
216 people have browsed it

Why Does Selenium's `span:contains('string')` Selector Fail, and How Can I Fix It?

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

When attempting to find an element using CSS selector with span:contains('string') in Python Selenium for Firefox, you may encounter the error:

selenium.common.exceptions.InvalidSelectorException: Message: Given css selector expression "span:contains('string')" is invalid: InvalidSelectorError: 'span:contains('string')' is not a valid selector: "span:contains('string')"
Copy after login

This issue arises because the :contains pseudo-class is not supported by CSS specifications nor natively by Firefox or Chrome. It was exclusive to the Selenium 1.0 Sizzle Selector Engine, but WebDriver does not support such selectors.

Alternative Solutions:

  • Use attribute selectors:

    element = "span[attribute_name=attribute_value]"
    Copy after login
  • Use XPath, which supports text(), contains(), and normalize-space() methods:

    element = my_driver.find_element_by_xpath("//span[text()='Control panel']")
    Copy after login
  • Employ jQuery, which supports CSS selectors:

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

Trivia:

  • CSS selectors are not natively supported in browser consoles, but jQuery's $() shortcut overrides document.querySelector to enable their use when jQuery is present on the page.

The above is the detailed content of Why Does Selenium's `span:contains('string')` Selector Fail, and How Can I Fix It?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
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