Using XPath with CasperJS QuerySelectorAll Doesn't Work

For some reason, when I try to run the following code:

var casper = require('casper').create(); var x = require('casper').selectXPath; var links = []; casper.start('http://www.website.com'); function getLinks() { var links = document.querySelectorAll(x('//*[@id="horizontalList"]/li[@class="paddingRight6"]/a'); return Array.prototype.map.call(links, function(e) { return e.getAttribute('href') }); } casper.then(function() { links = this.evaluate(getLinks); this.echo(links); } casper.run(); 

Returns a null object, but when I use the same xpath selector in combination with the thenClick method, everything works fine and the URL changes. Why is this so?

+6
source share
2 answers

So it turns out that the querySelectorAll method does not actually support XPath. This is actually not casperjs at all and is supported by the browser, so it accepts CSS3 selectors, not XPath. It was difficult for me to understand this, so I thought that I would put it in case someone else ran into this problem. You must use the CSS3 selector for this in casperjs, so the line:

 var links = document.querySelectorAll(x('//*[@id="horizontalList"]/li[@class="paddingRight6"]/a'); 

Required to change to:

 var links = document.querySelectorAll('ul#horizontalList li.paddingRight6 a'); 

Happy hack

+9
source

The function below works for me using Xpath.

 function getLinks() { var links =__utils__.getElementsByXPath('//*[@id="horizontalList"]/li[@class="paddingRight6"]/a'); return Array.prototype.map.call(links, function(e) { return e.getAttribute('href'); }); } 
+2
source

All Articles