Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get an array of elements from findElement(By.className())

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
}
like image 519
Jared Mark Shillingburg Avatar asked Jan 30 '16 04:01

Jared Mark Shillingburg


People also ask

How do I search for an element in className?

We can find an element using the attribute class name with Selenium webdriver using the locators - class name, css, or xpath. To identify the element with css, the expression should be tagname[class='value'] and the method to be used is By. cssSelector.

What is the difference between findElement () and findElements ()?

findElement() is used to find a webElement on a webpage. driver. findElements() is used to find a List of webElements matching the locator passed as parameter. In case the same locator matches multiple webElements then findElement method returns the first web element found.

How do you select all elements with the same class?

To select elements by a given class name, you use the getElementsByClassName() method: let elements = document. getElementsByClassName('className');

How do you use the findElement method?

FindElement() Method:This command is used to access any single element on the web page. It will return the object of the first matching element of the specified locator. It will throw NoSuchElementException when it fails to identify the element.


1 Answers

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
    });
});
like image 127
Jonathan Lonowski Avatar answered Oct 25 '22 14:10

Jonathan Lonowski