我正在测试一个输出一些数据的页面,我想将该数据捕获到JSON对象中。数据显示如下(以html为单位)
<cards>
<card>
<div id="name">Joe</div>
<div id="web">
<a target="_blank" href="http://joessite.com">joessite.com</a>
</div>
</card>
<card>
<div id="name">Frank</div>
<div id="web">
<a target="_blank" href="http://frankssite.com">frankssite.com</a>
</div>
</card>
</cards>
我希望得到的JSON对象是:
[ {
name: "Joe",
web: {
text: "joessite.com",
link: "http://joessite.com"
}
},
{
name: "Frank",
web: {
text: "frankssite.com",
link: "http://frankssite.com"
}
} ]
所以我写了下面的代码:
var cardDataToJSON = function() {
var result = {};
$$('cards card').each(function (card) {
card.$('#name').getText().then(function (text) { result["name"] = text; });
var web = {};
card.$('#web').getText().then(function (text) {
web["text"] = text;
});
card.$('#web').getAttribute('href').then(function (href) {
web["href"] = href;
});
result.web = web;
});
return result;
};
不幸的是,我的实际结果是(请注意第一个“ web”为空白)。
[ {
name: "Joe",
web: { }
},
{
name: "Frank",
web: {
text: "frankssite.com",
link: "http://frankssite.com"
}
} ]
我做错了什么或需要改进我的代码?
(我正在使用量角器版本3.2.2)
我会用map()
同protractor.promise.all()
:
var cardDataToJSON = function() {
return $$('cards card').map(function (card) {
var name = card.$('#name').getText(),
web = card.$('#web a').getText(),
href = card.$('#web a').getAttribute('href');
return protractor.promise.all([name, web, href]).then(function (values) {
return {
name: values[0],
web: {
text: values[1],
link: values[2]
}
}
});
});
};
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句