Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 364
Hyung Kyu Park Avatar asked Sep 14 '15 18:09

Hyung Kyu Park


2 Answers

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.

like image 25
Zakaria Acharki Avatar answered Oct 19 '22 09:10

Zakaria Acharki


<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.

like image 161
Artjom B. Avatar answered Oct 19 '22 10:10

Artjom B.