InvalidSelectorException Error while trying to get text from div class in Selenium Python

Viewed 199

I'm trying to get text using Selenium WebDriver and here is my code. Please note that I don't want to use XPath, because in my case the ID gets changed on every relaunch of the web page.

My code:

driver.find_element_by_class_name("05uR6d").text

HTML:

<div class="O5uR6d">to fasten stuff</div>

Error:

selenium.common.exceptions.InvalidSelectorException: Message: invalid selector: An invalid or illegal selector was specified (Session info: chrome=88.0.4324.150)

Error is specific to the line of code I mentioned above.

How can I fix this?

2 Answers

Use this xpath:

driver.find_element_by_xpath("//div[contains(text(),'to fasten stuff')]")

Or this CSS:

driver.find_element_by_css_selector(".O5uR6d")

If both won't work, improve your question by adding more data of HTML you are looking at.

It can be done using multiple ways let me try to explain most of them.

  1. Get element by class name.

this is the most easiest solution to get any element by class name you can simply do is:

driver.find_element_by_class_selector('foo');

  1. Get Element by xpath

This is a bit tricky one, you can apply xpath either the class name, title, id or whatever remains same. it also works even if there's a text inside your div. For example:

driver.find_element_by_xpath("//tagname[@attribute='value']")

or in your case:

driver.find_element_by_xpath("//div['class='O5uR6d']")

or you can do something like @vitaliis said

driver.find_element_by_xpath("//div[contains(text(),'to fasten stuff')]")

You can read more about xpath and how to find it on this link

  1. Get Elements by ID:

You can also get the element from id if there's any that's static: driver.find_element_by_id('baz')

  1. Get Elements by Name:

Get Elements by name using the following syntax: driver.find_element_by_name('bazz')

  1. Using CSS Selectors:

You can also use the css selectors to find the elements. Consider a following tag that has some attributes: <p class="content">Site content goes here.</p>

You can get this element by: driver.find_element_by_css_selector('p.content')

You can read more about it over here

Related