How can I get text content of multiple elements with Python Selenium?
python, selenium
Solution
Actually, when you do
text = driver.find_element_by_class_name("m-b-none").text
You will get the first element that is matched, and this element possesses, thanks to Selenium, an attribute whose name is `text`. A contrario, when you do
matched_elements = driver.find_elements_by_class_name("m-b-none")
^
it will match all corresponding elements. Given that `matched_elements` is a list, and that this list is a Python-native one, (it is not, for example, a Selenium-modified object which has `text` as attribute), you will have to iter over it, and iteratively get the text of each element. As follows
texts = []
for matched_element in matched_elements:
text = matched_element.text
texts.append(text)
print(text)
Or if you want to leave your code unchanged as possible, you can do it in one line:
texts = [el.text for el in driver.find_elements_by_class_name("m-b-none")]
Problem
Here is my code: ``` def textfinder(): try: textfinder1 = driver.find_elements_by_class_name("m-b-none").text except NoSuchElementException: pass print("no such element") print(textfinder1) ``` It works only when I use find_element. When I use find_elements, it gives me error "list" object has no attribute "text". I understand that it returns a list, but I just don’t know how to "read" it. When I remove .text from the command, I don’t get any error, but some weird data, but I need the text content of the class.