如何获取从XPATH请求返回的对象的迭代值。
我有这个HTML模板:
<div class="item">
<span class="light">Date</span>
<a class="link" href="">2018</a>
(4pop)
</div>
<div class="item">
<span class="light">From</span>
<span>
<a class="link" href="" title="Bob" itemprop="url"><span itemprop="name">Bob</span></a>,
</span>
<span>
<a class="link" href="" title="Peter" itemprop="url"><span itemprop="name">Peter</span></a>
</span>
</div>
<div class="item">
<span class="light">For</span>
<a class="link" href="">Bak</a>,
<a class="link" href="">Cam</a>,
<a class="link" href="">Oli</a>
</div>
<div class="item">
<span class="light">Nat</span>
<a class="link" href="">Cool</a>
</div>
</div>
还有我的Javascript代码:
var doc = new DOMParser().parseFromString(HTMLContent,'text/html');
var infos = doc.evaluate('//div[@class="item"]/span[1]', doc, null, XPathResult.ANY_TYPE, null);
var nodes = [];
for(var node = infos.iterateNext(); node; node = infos.iterateNext()) {
nodes.push(node);
console.log(node.textContent);
// Until here, all things works well ! Except the code from here:
var nodde = node.nextElementSibling.attributes;
nodde.forEach(function(item){
console.log(item);
});
}
我的目标是获取每个类别的相应值,例如:
Date = 2018, (4pop)
From = Bob, Peter
For = Bak, Cam, Oli
Nat = Cool
我尝试迭代:node.nextElementSibling.attributes
,但没有成功!
我尝试过的事情:
var nodde = node.nextElementSibling.attributes;
nodde.forEach(function(item){
console.log(item);
});
您可以在Javascript代码上对其进行检查,但是很遗憾,这将导致空结果。
请问有没有办法得到预期的结果?
答案 0 :(得分:1)
一旦获得商品,您就可以遍历childNodes
,其中包括标签和文本。
var items = document.evaluate('//div[@class="item"]', doc, null, XPathResult.ANY_TYPE, null);
while (item = items.iterateNext()) {
var values = [];
var nodes = item.childNodes;
for (var i = 2; i < nodes.length; i++) {
var value = nodes[i].textContent.trim().replace(',', '');
if (value.length) values.push(value);
}
console.log(item.getElementsByClassName('light')[0].innerText + " = " + values.join(', '));
}
打印:
Date = 2018, (4pop)
From = Bob, Peter
For = Bak, Cam, Oli
Nat = Cool