How to Handle \'Selenium.common.exceptions.InvalidSelectorException\' with \'span:contains(\'string\')\' in Selenium Python Firefox?

DDD
Release: 2024-10-18 22:00:04
Original
833 people have browsed it

How to Handle

Error: "Selenium.common.exceptions.InvalidSelectorException" with "span:contains('string')" in Selenium Python Firefox

When trying to locate an element using CSS selectors with the "contains" function, such as "span:contains('Control panel')", you may encounter the following error:

selenium.common.exceptions.InvalidSelectorException: Message: 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

Explanation:

This error occurs because the ":contains" pseudo-class is not supported in native CSS selectors by Firefox or Chrome. It was previously used in the Sizzle Selector Engine that Selenium 1.0 relied on, but was dropped in WebDriver due to inconsistencies across browsers.

Solution 1: Use Other CSS Attributes

Instead of using the ":contains" pseudo-class, search for the element using a different CSS attribute, such as class, id, or other identifying properties. For example:

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

Solution 2: Use XPath

XPath supports the ":contains" pseudo-class, so you can use it to locate the element:

  • 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

Solution 3: Use jQuery

Alternatively, you can use jQuery to locate the element with the "contains" function:

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

The above is the detailed content of How to Handle \'Selenium.common.exceptions.InvalidSelectorException\' with \'span:contains(\'string\')\' in Selenium Python Firefox?. 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!