14

ドキュメントによると、名前で単一の属性を取得する.getAttribute()には、次のように使用できWebElementます。

var myElement = element(by.id('myId'));
expect(myElement.getAttribute('myAttr')).toEqual('myValue');

しかし、要素が持つすべての属性を取得するにはどうすればよいでしょうか?

分度器 APIには、このユースケース/機能に関する情報はありません。

4

4 に答える 4

1

分度器 API の実装外であるbrowser.executeScript()ため、分度器 API の代わりに関数呼び出しを使用する必要があります。Element.attributes

var elem = element(by.id('runButton'));
browser.executeScript("return arguments[0].attributes", elem.getWebElement())
    .then(function (attrs) {
        console.log(attrs.length);    // outputs numbers of attributes.
        // access collection of Attr objects
        console.log(attrs[0].isId);   // outputs `true`
        console.log(attrs[0].name);   // outputs `id`
        console.log(attrs[0].value);  // outputs `runButton`
    });

attributesと言うときは、DOM モデルのコンテキストでは配列ではなく、名前付きのマップ構造を意味することに注意してください。つまり、 NamedNodeMapを使用してAttrオブジェクトのコレクションにアクセスする必要があります。

@alecxeの回答と同じように、反復部分なしで機能します。

于 2015-01-07T16:46:26.480 に答える
1

executeScript()属性を読み取る属性のリストを形成するスクリプトを実行するために使用しますelement.attributes(内部の js 部分は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);
    });

ここattrsには、属性名としてのキーと属性値としての値を持つ要素属性の辞書/オブジェクトが含まれます。

デモ ( angularjs.org チュートリアル ページを使用して、 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': '' }

それほど美しくコンパクトではありませんが、私にとってはうまくいきます。より良い代替案を見つけていただければ幸いです。


更新 (上記のアプローチの改善):

通常の関数を定義して渡す場合にも機能します。

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);
});
于 2014-12-30T00:52:00.547 に答える