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

后端 未结 1 671
半阙折子戏
半阙折子戏 2021-01-13 11:22

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 =         


        
1条回答
  •  被撕碎了的回忆
    2021-01-13 12:01

    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
        });
    });
    

    0 讨论(0)
提交回复
热议问题