简体   繁体   中英

How do I get the text inside of an element using Python Selenium?

So, I'm trying to get the text inside of all of the elements with the class names "letter-grade" and "course-name".

Here's what I've tried so far:

grades = browser.find_elements_by_class_name('letter-grade').__getattribute__('text')
classes = browser.find_elements_by_class_name('course-name').__getattribute__('text')
print(grades)
print(classes)

I've also tried doing print(grades.text) & print(classes.text) , to no avail.

    element = driver.find_elements_by_class_name('letter-grade')
    for element in elements:
    print element.text

if you want to get attribute text

    item = element.get_attribute("attribute name")
    print item.text

also you can't use find_elements_by_class_name if you are dealing with single web element, you can always refer find_element_by_class_name while dealing with individual element. find_elements_by_class_name will return list and you need to iterate through that list when you are dealing with list of web elements.

You can do it using the following code:

grades = browser.find_elements_by_class_name("letter-grade")
classes = browser.find_elements_by_class_name("course-name")

grades_text = [grade.text for grade in grades]
classes_text = [class_.text for class_ in classes]

print(grades_text)
print(classes_text)

It' called list comprehension in Python (3th and 4th lines above). For getting the text from an element the text attribute/property is used from Selenium.

I hope it helps you!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM