John Doe
John Doe

Reputation: 405

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?

Upvotes: 7

Views: 7199

Answers (2)

Spy1984
Spy1984

Reputation: 89

If you want to get html content of a particular xpath with phantomjs.. :-)

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);

Upvotes: 0

John Doe
John Doe

Reputation: 405

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);
});

Upvotes: 13

Related Questions