6

I am writing a script in node.js for selenium that will go to a page and grab the innerhtml of a certain css class and store them in an array.

var element = driver.findElement(By.className("hll"));
element.getInnerHtml().then(html){
    //returns 1 of the elements html where I want multiples
}
Jonathan Lonowski
  • 121,453
  • 34
  • 200
  • 199
  • Sorry. Could you please clarify what your question is? If it's how to find multiple elements, begin with the plural [`.findElements()`](http://seleniumhq.github.io/selenium/docs/api/javascript/class_webdriver_WebDriver.html#findElements). – Jonathan Lonowski Jan 30 '16 at 05:22
  • I just started learning selenium last night so apologies. If I run: var element = driver.findElements(By.className("hll")); how do I get the innerhtml of each index – Jared Mark Shillingburg Jan 30 '16 at 05:26

1 Answers1

12

To retrieve the html of multiple elements, you can use driver.findElements() to find all matches elements. This will provider a Promise that resolves with the elements in an Array.

var pendingElements = driver.findElements(By.className('h11'))

pendingElements.then(function (elements) {
    // ...
});

You'll need to iterate over the collection and request each element's HTML. You can use the Array's .map() to create a collection of promises from getInnerHtml():

var pendingHtml = elements.map(function (elem) {
    return elem.getInnerHtml();
});

To wait for them to be resolved, you can pass the collection to promise.all().

promise.all(pendingHtml).then(function (allHtml) {
    // ...
});

Note, you'll need a reference to Selenium's promise for that.

var promise = require('selenium-webdriver').promise;

Combined:

// ...

var promise = require('selenium-webdriver').promise;

var pendingElements = driver.findElements(By.className('h11'))

pendingElements.then(function (elements) {
    var pendingHtml = elements.map(function (elem) {
        return elem.getInnerHtml();
    });

    promise.all(pendingHtml).then(function (allHtml) {
        // `allHtml` will be an `Array` of strings
    });
});
Jonathan Lonowski
  • 121,453
  • 34
  • 200
  • 199