Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get text from div using Selenium

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.

like image 481
Hayden Avatar asked Nov 15 '25 19:11

Hayden


1 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)
like image 118
Amit Verma Avatar answered Nov 18 '25 08:11

Amit Verma



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!