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
Patricia ArquetteOriginal
2024-12-13 13:44:10214browse

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

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]"
  • Use XPath, which supports text(), contains(), and normalize-space() methods:

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

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

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!

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