【发布时间】:2022-01-13 23:23:55
【问题描述】:
大家好,我希望使用 Xpath 从一些 html 中获取 href 链接,如下所示:
function getStuff(Path) {
var txt = '';
var cnt = 0;
var nodes = document.evaluate(Path, document, null, XPathResult.ANY_TYPE, null);
var result = nodes.iterateNext();
var Json = '{testing:[';
while (result) {
if (cnt != 10) {
//console.log('Result: ', result);
txt += '{href:' + result + '},';
result = nodes.iterateNext();
cnt++;
} else {
txt = txt.replace(/(^,)|(,$)/g, );
break;
}
}
return Json + txt + ']}';
}
console.log(getStuff("//html/body/div[1]/div/div/div/div/div/div/div/descendant::a[contains(@href, '?fref=pb')]/@href"));
输出如下:
{testing:[{href:[object Attr]},{href:[object Attr]},{href:[object A...etc etc
但是,如果我取消注释 console.log,它会像我需要的那样输出:
Result: href="/bob.barker.982?fref=pb"
Result: href="/bill.gates.982?fref=pb"
Result: href="/steve.jobs?fref=pb"
Result: href="/513845713656?fref=pb"
Result: href="/bill.murry?fref=pb"
Result: href="/m.c.hammer?fref=pb"
...etc etc
如何获得与console.log 相同但保存到txt+= 逻辑的输出?如果有更好的方法,请分享。
【问题讨论】:
标签: javascript xpath nodes element