Hyung Kyu Park
Hyung Kyu Park

Reputation: 265

How to get innerHTML using CasperJS?

I want to get attribute of only string in <em> tags of HTML page

enter image description here

I want to get "(868)"

1.

casper.then(function() {
     var word = require('utils').dump(this.getElementAttribute(x('//*[@id="content"]/div[2]/h4/em'), 'em'));
     console.log(word)
});

2.

casper.then(function() {
    var word = require('utils').dump(this.getElementAttribute(h4[class="head"], 'em'));
    console.log(word)
});

I tried both but it returns "null" How to solve the problem?

Upvotes: 5

Views: 11408

Answers (2)

Zakaria Acharki
Zakaria Acharki

Reputation: 67495

Take a look at documentation FAQ Can I access & manipulate DOM elements directly from the CasperJS environment?.

In the both of examples that you added in your question you tried to get the em element as an attribute of h4 and that wrong because em is a child and not attribute of h4 tag, so to select textContent of an element you can try to use querySelector with evaluate function like following :

casper.then(function() {
    var text = this.evaluate(function(){
        return document.querySelector("h4.head em").textContent;
    });

    var word = require('utils').dump(text);
    console.log(word);
}

Hope this helps.

Upvotes: 3

Artjom B.
Artjom B.

Reputation: 61892

<em> is not an element attribute. It's an element itself. casper.getElementAttribute(selector, attribute) will correctly retrieve the attribute text of an element, but your want to get the element text.

You can use casper.fetchText(selector) for that. Note that fetchText() will concatenate the contents of all matched elements into one string. If you don't want that, you either need to make sure that the selector only matches a single element or use other functions such as casper.getElementInfo(selector).text.


Your second snippet cannot work, because you forgot " around the selector and because of the above reason.

Upvotes: 7

Related Questions