How to locate element using text() facing exception(selenium+python)? How to locate element using text() facing exception(selenium+python)? selenium selenium

How to locate element using text() facing exception(selenium+python)?


Since your using a xpath expression, use driver.find_element_by_xpath instead

driver.find_element_by_xpath("//span[contains(text(),'App')]")

hope this helps


You Are Giving Xpath to css selector it's wrong!

you need to give xpath to xpath function not css selector function

That's Why You Are Getting That Error

Try This:

driver.find_element_by_xpath("//span[contains(text(),'App')]")


This error message...

selenium.common.exceptions.InvalidSelectorException: Message: Given css selector expression "//span[contains(text(),'App')]" is invalid: InvalidSelectorError: '//span[contains(text(),'App')]' is not a valid selector: "//span[contains(text(),'App')]"

...implies that the css selector expression which you have used is not a valid css selector.


Using to locate element by text is not supported through Selenium yet (although it may work in the developer tools console). The only possibility is

You can find a detailed discussion in selenium.common.exceptions.InvalidSelectorException with "span:contains('string')"


So using css_selectors as per the HTML you have provided you can use the following Locator Strategy:

span.menu-text

However your code trials pretty much resembles to xpath. So you need to change find_element_by_css_selector to find_element_by_xpath. So effectively, the line of code will be:

driver.find_element_by_xpath("//span[text()='Download App']")

As an alternative,

driver.find_element_by_xpath("//span[contains(., 'App')]")