Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XPath lookup doesn't work in PhantomJS

I'm trying to get XPath working with 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();

This is being executed upon page load and always returns null whereas querySelector seems to work correctly:

var divs = page.evaluate(function(s) {
  return document.querySelector(s);
}, 'div');

Did I miss something in this particular XPath evaluate sample?

like image 506
John Doe Avatar asked Oct 25 '13 12:10

John Doe


1 Answers

I have finally found out that the call document.evaluate must be embraced with a page.evaluate call like the following:

page.evaluate(function() {
    document.evaluate(
        '//div',
        document,
        null,
        XPathResult.ORDERED_NODE_ITERATOR_TYPE,
        null);
});
like image 91
John Doe Avatar answered Nov 23 '22 11:11

John Doe