我正在使用Cheerio js抓取一个网站,我有一个数组中的表格行列表,当我在for循环中使用$ .html('text')修改内在HTML的内容似乎有效但是一旦函数退出,我将丢失修改后的文本:
var cheerio = require('cheerio');
var bands = [];
var res = function (data) {
for (var j=0; j < data.length; j++) {
var perline = data[j];
var $ = cheerio.load(perline);
var chline = $('[class^="eventSlot"]');
for (var i=0; i < chline.length; i++) {
console.log($(chline[i]).html()); // looks correct
$(chline[i]).html('some text'); // modify inner HTML
console.log($(chline[i]).html()); // looks modified
}
bands.push(perline);
}
return bands;
};
var html = ['<td>11/04/2014</td><td><span class="eventSlot slot1 headliner">Band1</span><span class="eventSlot slot2">Band2</span></td><td>',
'<td>11/04/2014</td><td><span class="eventSlot slot1 headliner">Band3</span></td>'];
console.log(res(html)); // contents are not modified from original html
答案 0 :(得分:1)
您需要使用Cheerio的bands
函数将您要推送到.html()
的每一行渲染为HTML。如果第13行更改为:
bands.push(perline.html());
以下是完整代码:
var cheerio = require('cheerio');
var html = ['<td>11/04/2014</td><td><span class="eventSlot slot1 headliner">Band1</span><span class="eventSlot slot2">Band2</span></td><td>',
'<td>11/04/2014</td><td><span class="eventSlot slot1 headliner">Band3</span></td>'];
var res = function (data) {
for (var j=0; j < data.length; j++) {
var perline = data[j];
var $ = cheerio.load(perline);
var chline = $('[class^="eventSlot"]');
for (var i=0; i < chline.length; i++) {
$(chline[i]).html('some text'); // modify inner HTML
}
bands.push(perline.html()); // Render the HTML back to text
}
return bands;
};
var bands = [];
console.log(res(html)); // contents *ARE* modified from original html
需要考虑的事项:您的方法似乎有点奇怪,因为您要逐行转换HTML。也许我错过了你的确,但我认为你会在一个更大的块上运行,然后在最后转换为HTML。
答案 1 :(得分:0)
您可能需要bands.push($.html())
,因为cheerio不会修改原始源数据。它修改了它自己的DOM模型。你必须调用一些cheerio渲染方法来检索修改后的模型