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
}
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.
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.
To select elements by a given class name, you use the getElementsByClassName() method: let elements = document. getElementsByClassName('className');
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.
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
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With