XPath search does not work in PhantomJS

I am trying to get XPath to work 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 done when the page loads and always returns null, while querySelector works correctly:

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

Did I miss something in this particular XPath example for evaluation?

+7
xpath phantomjs
source share
2 answers

I finally found out that the call to document.evaluate should be considered by calling page.evaluate as follows:

 page.evaluate(function() { document.evaluate( '//div', document, null, XPathResult.ORDERED_NODE_ITERATOR_TYPE, null); }); 
+13
source share

If you want to get the html content of a specific 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); 
0
source share

All Articles