【问题标题】:node.js - Parsing a specific table in a html page that has multiple tables using cheerionode.js - 使用 Cheerio 解析具有多个表的 html 页面中的特定表
【发布时间】:2017-08-10 02:09:19
【问题描述】:

这是我的示例 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 来解析表格,但不幸的是,我无法选择特定的表格,因为表格没有任何ID 或属于不同的类。 下面的代码从两个表中提取所有行。我必须将输出与已知元素(例如“element2”)进行比较,以修复可用于识别表的索引。但是有没有更好的方法使用cheerio 来获取页面上的第一个表或只获取页面上的第二个表?

var $ = cheerio.load(sampleHTML);
$('table tr').each(function (i, element) { ..} 

【问题讨论】:

标签: javascript dom cheerio


【解决方案1】:

是的,有多种方法:

1) 使用 :first-of-type:last-of-type:nth-of-type(n):first-child:last-childnth-child(n) 选择器。一些例子:

// 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() 本身)。有了这些,您可以选择所有tables,过滤到您想要的table,然后在该表中找到所有trs。

// 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')

【讨论】:

  • 完美!尝试了第二种过滤方法。像魅力一样工作。谢谢
猜你喜欢
  • 2017-10-31
  • 1970-01-01
  • 2013-10-28
  • 2018-05-29
  • 2020-06-10
  • 1970-01-01
  • 1970-01-01
  • 2011-11-14
相关资源
最近更新 更多