页面中有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,仅显示元素对象。
答案 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。选项
您可以使用async
和await
,以便编写同步代码。
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);
};
})