elf
elf

Reputation: 67

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

HTML

<span class="menu-text">Download App</span>

my code to locate the element

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

or

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

when I run it, an exception reported:

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

Upvotes: 3

Views: 533

Answers (3)

undetected Selenium
undetected Selenium

Reputation: 193088

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

Upvotes: 0

Hamza Lachi
Hamza Lachi

Reputation: 1064

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

Upvotes: 0

Melan
Melan

Reputation: 458

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

Upvotes: 6

Related Questions