Get text from div using Selenium

Question:

I’m using Selenium and Python to extract information from a page.

Here is the div I want to extract from:

<div class="_2v66">5</div>

I want to extract the value "5".

Here is the Python I have written:

element = browser.find_elements_by_class_name('_2v66').getText

print('Views:')
print(element)

When I run this script, I get the following message:

Traceback (most recent call last):
  File "<string>", line 95, in <module>
AttributeError: 'list' object has no attribute 'getText'
[Finished in 15.478s]

Solution:

Although I originally thought the div class was unique, after a closer inspection of the page I realized that it is not a unique div and therefore the solution was as follows:

browser.get(('https://www.facebook.com/example_page_1/insights/?section=navVideos'))

browser.implicitly_wait(60)

# find_elements_by_class_name - Returns the div in which the metrics are found
elements = browser.find_elements_by_class_name('_2v66')

for e in elements:
    print(e.text)

The browser.implicitly_wait was crucial to allow the page to load. The errors I was receiving with regards to the object no existing were because of that.

Asked By: Hayden

||

Answers:

Use just .text

element = browser.find_element_by_class_name('_2v66').text

If there are multiple elements, you’ll have to loop through them.

elements = browser.find_elements_by_class_name('_2v66')
for e in elements:
    print(e.text)
Answered By: Amit

As per the HTML you have provided to extract the text 5, instead of using find_elements* you need to use find_element and you can use the following solution:

element = browser.find_element_by_class_name('_2v66').text
print(element)

Note A: The Selenium-Python client doesn’t have any method getText, but instead text.

Note B: You have to ensure that this particular <div> tag can be uniquely identified through the class attribute _2v66.

Answered By: undetected Selenium
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.