Search code examples
javascriptphantomjscasperjs

How to get a text in tag with casperjs?


I have a html-code:

<div class="div_table_body">
<table class="part_listing">
    <tr><td>sometext</td></tr>
    <tr><td>sometext2</td></tr>
    ...
</table>
</div>

I try to get a text in tag 'td' with casperjs:

function getLinks() {
    var tr = document.querySelectorAll('div.div_table_body table.part_listing tr');
    return Array.prototype.map.call(tr, function (e) {
        return e.getHTML('td', true);
        });
    }
    casper.then(function () {
        links = this.evaluate(getLinks);
        console.log('links ' +links);
        });

But I get a NULL, please help to understand what in this code is wrong?


Solution

  • This will update getLinks to create and return an area containing outerHTML strings for the td. You can't use the getHTML() inside getLinks. Casper evaluates the getLinks and executes this on a page, so that needs to be vanilla JS.

    function getLinks() {
        var tr = document.querySelectorAll('div.div_table_body table.part_listing tr'); 
        return Array.prototype.map.call(tr, function (e) {
            return e.querySelector('td').outerHTML;
        });
    }
    

    To fetch with Casper only:

    casper.start('http://www.example.com', function() {
        this.getHTML('div.div_table_body table.part_listing tr > td', true); 
    });
    

    I updated your selector to select tds from the trs.