我正在尝试让XPath使用PhantomJS 1.9.2:
var getElementsByXPath = function(xPath) {
return document.evaluate(
xPath, document, null, XPathResult.ORDERED_NODE_ITERATOR_TYPE, null);
};
var root = getElementsByXPath("//div").iterateNext();
这是在页面加载时执行的,并且始终返回null,而querySelector似乎正常工作:
var divs = page.evaluate(function(s) {
return document.querySelector(s);
}, 'div');
我在这个特定的XPath评估样本中是否遗漏了什么?
答案 0 :(得分:13)
我终于发现调用document.evaluate必须包含一个page.evaluate调用,如下所示:
page.evaluate(function() {
document.evaluate(
'//div',
document,
null,
XPathResult.ORDERED_NODE_ITERATOR_TYPE,
null);
});
答案 1 :(得分:0)
如果你想用phantomjs获取特定xpath的html内容..: - )
var xpath= '//*[@id="2b"]';
var address= 'www.mywebadress.com';
page.open(address, function(status) {
setTimeout(grabHtml, 2500);
});
function grabHtml() {
var html = page.evaluate(function(xpath) {
if (document.evaluate) {
var xPathRes = document.evaluate(xpath, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null)
if (xPathRes.singleNodeValue) {
var c = html.singleNodeValue.innerHTML;
} else if (xPathRes) {
var c = "No content found!";
}
} else {
var c = "does not support the evaluate method!";
}
return c;
}, xpath);
console.log(html);