Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using XPath with CasperJS QuerySelectorAll not working

For some reason when I try running 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 very same xpath selector in conjunction with the thenClick method, everything works fine and the url changes. Why on earth is that?

like image 583
Slater Victoroff Avatar asked Apr 02 '13 20:04

Slater Victoroff


2 Answers

So, it turns out that the querySelectorAll method doesn't actually support XPath. In fact it doesn't come from casperjs at all, and is supported by the browser, which is why it accepts CSS3 selectors, and not XPath. It was tough for me to figure that out so I figured I would put this up in case anyone else had this problem. You have to use CSS3 selectors for this within casperjs so the line:

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

Needs to be changed to:

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

Happy hacking

like image 133
Slater Victoroff Avatar answered Sep 23 '22 12:09

Slater Victoroff


The below function works for me with 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');
});
}
like image 35
Apu V Avatar answered Sep 25 '22 12:09

Apu V