Using XPath with CasperJS QuerySelectorAll not working
Asked Answered
S

2

6

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?

Southsouthwest answered 2/4, 2013 at 20:22 Comment(0)
S
10

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

Southsouthwest answered 2/4, 2013 at 20:22 Comment(1)
It's not CasperJS's querySelectorAll() method... it's the browser's. The spec is designed only for use with CSS selectors: w3.org/TR/selectors-api XPath expressions, while they're used to select things, are a different family altogether.Fescue
G
2

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');
});
}
Gormless answered 23/1, 2014 at 17:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.