使用量角器获取所有元素的ID

时间:2018-06-24 18:43:06

标签: javascript protractor

页面中有5个iframe元素,我正在尝试使用量角器来查找所有5个元素的ID。

正确的方法是什么

element.all(by.tagName('iframe')).then(function(arr) {
    console.log("lenthg" ,arr.length) //prints 5
        arr.forEach(function(arr1) {
            console.log("arr1", arr1.getAttribute('id'))
        });
});

此代码不提供ID,仅显示元素对象。

1 个答案:

答案 0 :(得分:2)

您将获得元素对象,因为函数getAttribute返回了一个Promise(请参阅here)。

因此,您有多种获取ID的可能性。

1。选项

您可以在then方法中打印ID。

element.all(by.tagName('iframe')).then(function(arr) {
    console.log("lenthg" ,arr.length) //prints 5
    arr.forEach(function(arr1) {
        arr1.getAttribute('id').then(function(id) {
            console.log("arr1", id);
        });
    });
});

2。选项

您可以等待所有5个承诺解决,然后再处理ID。

element.all(by.tagName('iframe')).then(function(arr) {
    console.log("lenthg" ,arr.length) //prints 5

    let idPromises = arr.map(function(arr1) {
        return arr1.getAttribute('id');
    });

    Promise.all(idPromises).then(function(ids) {
        ids.forEach(function(id) {
            console.log(id);
        });
    });

});

3。选项

您可以使用asyncawait,以便编写同步代码。

it('Your Test Name', async function() {

    ...

    let arr = await element.all(by.tagName('iframe'));
    console.log('lenth', arr.length) //prints 5

    for (let i = 0; i < arr.length; i++) {
        let id = await arr[i].getAttribute('id');
        console.log("arr1", id);
    };

})