node.js - 使用 cheerio 解析具有多个 table 的 html 页面中的特定 table
node.js - Parsing a specific table in a html page that has multiple tables using cheerio
这是我的示例 html。
<table class = "one">
<thead>..</thead>
<tbody>
<tr>
<td>"Element 1<td>
</tr>
</tbody>
</table>
<table class = "one">
<thead>..</thead>
<tbody>
<tr>
<td>"Element 2<td>
<td>"Element 3<td>
</tr>
</tbody>
</table>
我正在使用 cheerio 来解析 tables 但不幸的是,我无法 select 特定的 table 因为 tables 没有任何 ID 或属于不同的 类。
下面的代码从 table 中提取所有行。我必须将输出与已知元素(例如 "element2")进行比较,以修复可用于识别 table 的索引。但是有没有更好的方法使用 cheerio 获取页面上的第一个 table 或仅获取页面上的第二个 table?
var $ = cheerio.load(sampleHTML);
$('table tr').each(function (i, element) { ..}
是的,有多种方法:
1) 使用 :first-of-type
、:last-of-type
、:nth-of-type(n)
、:first-child
、:last-child
或 nth-child(n)
select要么。一些例子:
// to select rows in table 1:
$('table:first-of-type tr')
$('table:nth-child(1) tr')
// to select rows in table 2:
$('table:nth-of-type(2) tr')
$('table:last-child tr')
2) 使用内置的 .first()
、.last()
或 .eq(n)
过滤方法(或 .filter()
本身)。有了这些,您将 select 所有 table
过滤到您想要的 table
,然后在 table 中找到所有 tr
。
// to select rows in table 1:
$('table').first().find('tr')
$('table').eq(0).find('tr')
// to select rows in table 2:
$('table').last().find('tr')
$('table').filter(i => i === 1).find('tr')
这是我的示例 html。
<table class = "one">
<thead>..</thead>
<tbody>
<tr>
<td>"Element 1<td>
</tr>
</tbody>
</table>
<table class = "one">
<thead>..</thead>
<tbody>
<tr>
<td>"Element 2<td>
<td>"Element 3<td>
</tr>
</tbody>
</table>
我正在使用 cheerio 来解析 tables 但不幸的是,我无法 select 特定的 table 因为 tables 没有任何 ID 或属于不同的 类。 下面的代码从 table 中提取所有行。我必须将输出与已知元素(例如 "element2")进行比较,以修复可用于识别 table 的索引。但是有没有更好的方法使用 cheerio 获取页面上的第一个 table 或仅获取页面上的第二个 table?
var $ = cheerio.load(sampleHTML);
$('table tr').each(function (i, element) { ..}
是的,有多种方法:
1) 使用 :first-of-type
、:last-of-type
、:nth-of-type(n)
、:first-child
、:last-child
或 nth-child(n)
select要么。一些例子:
// to select rows in table 1:
$('table:first-of-type tr')
$('table:nth-child(1) tr')
// to select rows in table 2:
$('table:nth-of-type(2) tr')
$('table:last-child tr')
2) 使用内置的 .first()
、.last()
或 .eq(n)
过滤方法(或 .filter()
本身)。有了这些,您将 select 所有 table
过滤到您想要的 table
,然后在 table 中找到所有 tr
。
// to select rows in table 1:
$('table').first().find('tr')
$('table').eq(0).find('tr')
// to select rows in table 2:
$('table').last().find('tr')
$('table').filter(i => i === 1).find('tr')