How to get innerHTML using CasperJS?
Asked Answered
C

2

5

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?

Cornuted answered 14/9, 2015 at 18:44 Comment(0)
L
7

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

Luetic answered 14/9, 2015 at 19:24 Comment(1)
Thank you very much. I used casper.fetchText("h4.head em") and it works.Cornuted
S
3

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.

Splinter answered 14/9, 2015 at 19:41 Comment(1)
@Zakaria Acharki Thanks a lot!! but it returns string include " " so another answer was better. Thank you for your answer again.Cornuted

© 2022 - 2024 — McMap. All rights reserved.