How can I get text content of multiple elements with Python Selenium?

Question:

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.

Asked By: user3281831

||

Answers:

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")]
Answered By: keepAlive

You would need to reference each like an element of a list. Something like this:

textfinder1 = driver.find_elements_by_class_name("m-b-none")

for elements in textfinder1:
    print elements.text 
Answered By: William

The method find_elements_by_class_name returns a list, so you should do:

text = ''
textfinder1 = driver.find_elements_by_class_name("m-b-none")
for i in textfinder1:
  text += i.text + 'n' # Or whatever the way you want to concatenate your text
print(text)
Answered By: melhirech
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.