user3281831
user3281831

Reputation: 909

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

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.

Upvotes: 2

Views: 10031

Answers (3)

melhirech
melhirech

Reputation: 49

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)

Upvotes: 1

keepAlive
keepAlive

Reputation: 6665

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

Upvotes: 7

William
William

Reputation: 154

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 

Upvotes: 1

Related Questions