Get all element attributes using protractor

后端 未结 4 747
故里飘歌
故里飘歌 2020-12-17 15:54

According to the documentation, to get a single attribute by name you can use .getAttribute() on a WebElement:

var myElement = element(by.id(\'m         


        
4条回答
  •  隐瞒了意图╮
    2020-12-17 16:30

    Use executeScript() to execute a script that forms a list of attributes reading them from element.attributes (js part inside is taken from here):

    var elm = element(by.id('runButton')).getWebElement();
    browser.executeScript(
        'var items = {}; \
         for (index = 0; index < arguments[0].attributes.length; ++index) { \
             items[arguments[0].attributes[index].name] = arguments[0].attributes[index].value \
         }; \
         return items;', elm).then(function (attrs) {
            console.log(attrs);
        });
    

    Here attrs would contain a dictionary/object of element attributes with keys as attribute names and values as attribute values.

    Demo (using angularjs.org tutorial page, getting all attributes for a header):

    $ node node_modules/protractor/bin/elementexplorer.js https://docs.angularjs.org/tutorial
    Getting page at: https://docs.angularjs.org/tutorial
    > var elm = element(by.tagName('header')).getWebElement();
    > browser.executeScript('var items = {}; for (index = 0; index < arguments[0].attributes.length; ++index) { items[arguments[0].attributes[index].name] = arguments[0].attributes[index].value }; return items;', elm).then(function (attrs) {
    ...     console.log(attrs);
    ... });
    { class: 'header header-fixed', 'scroll-y-offset-element': '' }
    

    Not really beautiful and compact, but works for me. Would be happy to see better alternatives.


    UPDATE (an improvement to the approach above):

    It would also work if I would define a regular function and pass it in:

    function getAllAttributes (arguments) {
        var items = {}; 
        for (index = 0; index < arguments[0].attributes.length; ++index) { 
            items[arguments[0].attributes[index].name] = arguments[0].attributes[index].value; 
        }
        return items;
    }
    
    browser.executeScript(getAllAttributes, elm).then(function (attrs) {
        console.log(attrs);
    });
    

提交回复
热议问题