在Cheerio.js的表格中迭代TR

我在使用我在节点服务器上使用的Cheerio.js的select器时遇到问题。 核心是基于jQuery,但是我真的不能使用原生jQuery相同的select。

我有一个DOM,大致看起来像这样:

<div class="test"> <table class="listing"> <thead><tr>few cells here</tr></thead> <tfoot></tfoot> <tbody><tr>These are the rows I want</tr></tbody> </table> </div> 

由于在“listing”类的页面上有两个表,所以我不能直接select它,所以我需要引用带有“test”类的div。 我可以运行jQuery的select将是这样的:

 $('div.test tbody tr') 

但这不适用于Cheerio。 如果我运行$('div [class =“test”] tr'),我得到了表上的所有行,甚至是行,所以这对我不起作用。

任何猜测?

更新:这是我正在执行的实际代码(不起作用):

 // Load the html var $ = cheerio.load(html, { normalizeWhitespace: true }); $('div.tillgodo tbody tr').each(function(){ console.log("Found credited course..."); var children = $(this).children(); var credits = parseFloat($(children[3]).text().replace(',', '.')); // We need to replace comma with a dot since parseFloats only supports dots by design var row = { "course" : $(children[1]).text().trim(), "grade" : null, "credits" : credits, "date" : $(children[4]).text() }; // Push course to JSON object console.log("Push course to object..."); console.log("------------------------------------------\n"); data.credited_courses.push(row); data.credited_courses_credits += parseFloat(credits); }); 

以下代码适用于第一个表格:

 $('tr.incomplete.course').each(function(i, tr){ console.log("This is course nr: " + parseInt(course_count+1)); console.log("Found incompleted course..."); var children = $(this).children(); var credits = parseFloat($(children[2]).text().replace(',', '.').match(/(\+|-)?((\d+(\.\d+)?)|(\.\d+))/)[0]); // Filter out any parentheses and odd characters var row = { "course" : $(children[1]).text(), "grade" : $(children[3]).text(), "credits" : credits, "date" : $(children[5]).text() }; // Sum the total amount of credits for all courses console.log("Add credits to incompleted_credits..."); data.incompleted_credits += credits; console.log("Push course to object..."); data.incompleted_courses.push(row); course_count++; }); 

当我说这不起作用意味着我返回的JSON对象不具有第二个表中的预期行。

更新2表我想刮:

 <div class="tillgodo"> <h2>Tillgodoräknanden</h2> <table class="listing"> <thead> <tr class="listingHeader"> <th>Kurskod</th> <th>Kursnamn</th> <th>Beslutsfattare</th> <th class="credits">Poäng</th> <th>Datum</th> </tr> </thead> <tfoot> <tr class="listingTrailer"> <td> </td><td colspan="2">Summa tillgodoräknade poäng: </td><td class="credits">10,5 </td><td> </td></tr> </tfoot> <tbody><tr> <td> </td><td>Valfria kurser </td><td>xxx </td><td class="credits">10,5 </td><td class="nobreak">2013-06-03 </td></tr> </tbody> </table> </div> 

最终更新(问题解决)我一直在使用的select器正在工作。 但源HTML格式不正确,根本没有任何标签。 浏览器(在我的情况下Chrome)解决了这个问题,但很难find真正的问题。

你可以试试$(div.test table.listing tr).text()

这将为您提供该表中所有tr标签的文本