Nazilil Asror
Nazilil Asror

Reputation: 21

How to get href attribute value in CasperJS?

here is what I do with the code to get the href value inside a elements:

var info = this.getElementsInfo(selector); // an array of object literals
for (var i = firstp; i < info.length; i=i+interval) {
    if(i==0)
        this.echo('"'+info[i].getAttribute('href')+'"');
    else
        this.echo(',"'+info[i].getAttribute('href')+'"');
}

Upvotes: 0

Views: 4139

Answers (2)

apeg3200
apeg3200

Reputation: 11

Follow these steps:

Get the path first

some variable = 'table#dgResults > tbody > tr:nth-child(1) > td > b a';

it goes (this only an explanation of "some variable"):

table[id="dgResults"] -> (couldn't add to the stupid gray box)

    tbody

      tr-> lst column

          b
              a -> all href tags are here 

Next use the the getElementsAttribute

var nextStep = this.getElementsAttribute(elem, 'href');

Then dump it:

utils.dump(nextStep);

You should see all the links when you dump it. Remember that this.getElementAttribute() returns 1 value between the tag and this.getElementsAttribute() returns ALL the values between the tags.

Upvotes: 1

Nazilil Asror
Nazilil Asror

Reputation: 21

I found something in the documentation and I can solve my problem with code like this:

var info = this.getElementsInfo(selector); // an array of object literals
for (var i = firstp; i < info.length; i=i+interval) {
    if(i==0)
        this.echo('"'+info[i].attributes.href+'"');
    else
        this.echo(',"'+info[i].attributes.href+'"');
}

and it works now.

The reason it didn't work before with getAttribute is that casper.getElementsInfo() returns a plain object representation of the DOM nodes and not the actual DOM nodes. As CasperJS (and PhantomJS for that matter) have two contexts, DOM nodes cannot be passed out of the page context (inside casper.evaluate()).

Upvotes: 2

Related Questions