2

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.

0

3 Answers 3

7

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")]
Sign up to request clarification or add additional context in comments.

Comments

1

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 

Comments

1

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.