How to Resolve InvalidSelectorException with \'span:contains(\'String\')\' in Selenium?

Mary-Kate Olsen
Release: 2024-10-18 21:58:30
Original
593 people have browsed it

How to Resolve InvalidSelectorException with

Invalid SelectorException in Selenium with "span:contains('String')"

When using Selenium in Python with Firefox, attempting to find an element using the CSS selector "span:contains('Control panel')" may result in the following error:

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

This error indicates that the provided CSS selector is invalid. According to Issue#987 and Issue#1547, the ":contains" pseudo-class is not supported by Firefox or Chrome.

Solution:

The ":contains" pseudo-class is not a standard CSS selector and should be replaced with an alternative attribute selector. For example:

<code class="python">element = "span[attribute_name=attribute_value]"</code>
Copy after login

Alternate XPaths:

If an attribute selector is not available, you can use one of the following XPaths:

element = my_driver.find_element_by_xpath("//span[text()='Control panel']")
element = my_driver.find_element_by_xpath("//span[contains(.,'Control panel')]")
element = my_driver.find_element_by_xpath("//span[normalize-space()='Control panel']")
Copy after login

jQuery Alternative:

<code class="javascript">$('span:contains("Control panel")')</code>
Copy after login

Note:

CSS selectors are not supported in the browser console, but JQuery provides a shortcut for document.querySelector. As such, JQuery may support CSS selectors if it is enabled on the page.

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