Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Quality Assurance

How can I extract text from: <div class="listview-total">Total: 4 Reservation(s)</div>

How can I extract text using Selenium from the following:
<div class="listview-total">Total: 4 Reservation(s)</div>

I want an object that contains the string "Total: 4 Reservation(s)"

1 Answer

Greg Kaleka
Greg Kaleka
39,018 Points

Are you talking about a javascript object? If so, the first step is to track down the element on the page. Since there's no id, you can't use document.getElementById() - you have to instead use document.getElementByClassName(), which returns a array. If you've only got the one element on your page with that class, then you can simply take the first element in that array, and use the attribute textContent to get the text between the tags.

Like so:

var theDiv = document.getElementsByClassName("listview-total")[0];
var text = theDiv.textContent

Let me know if this isn't what you're after!

Cheers :beers:

-Greg

Thanks Greg. This could work. I am going to try it. I am creating a Selenium web automation script and need to extract this text. I was thinking about using either the Selenium Webdriver CSS Selector method or the Xpath method.

Greg Kaleka
Greg Kaleka
39,018 Points

Ah ok - well if you're using Selenium, you can use selenium's By.className() method to get the element. Check out the docs here. Then you can use textContent as well, assuming you're writing your script in javascript.

You should check out the Selenium course here on Treehouse if you haven't already.

BTW, I took the liberty of changing the topic to Quality Assurance instead of CSS, since you're asking for Selenium tips :blush: