Reputation: 187
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?
Upvotes: 1
Views: 966
Reputation: 29047
CasperJS allows you to access the textContent
of elements using getElementsInfo()
and its corresponding .text
attribute:
Short Answer:
var td = this.getElementsInfo('.div_table_body > .part_listing > tbody > tr > td');
this.echo(td[0].text); // Result: sometext
Full Answer:
var casper = require('casper').create();
casper.start('https://www.example.com/', function () {
var td = this.getElementsInfo('.div_table_body > .part_listing > tbody > tr > td');
var td_array = [].map.call(td, function (element) {
return element.text.trim();
});
this.echo(td_array); // Result: sometext,sometext2
});
casper.run();
This will return an array containing [sometext, sometext2]
.
Upvotes: 1
Reputation: 13304
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 td
s from the tr
s.
Upvotes: 2