【问题标题】:How to iterate over rows of nth unnamed table如何遍历第 n 个未命名表的行
【发布时间】:2020-02-12 12:11:53
【问题描述】:

我正在尝试使用 Cheerio(类似于 jQuery)来操作一个看起来像这样的 HTML 页面:

<TABLE>
<!--- table body -->
</TABLE>
<!-- more html -->
<TABLE>
<!--- another table body -->
</TABLE>
<!-- more html -->
<TABLE>
  <TBODY>
    <TR>
      <TD>Column 1 value</TD>
      <!-- similar cols 2-5 -->
    </TR>
    <!-- more rows -->
  </TBODY>
</TABLE>
<!-- rest of page -->

也就是说,该页面上有三个 TABLE 元素,它们都没有 id。我需要第三个。我只想遍历表中的行并提取每行中的第一个、第三个和第五个单元格。

应该很简单吧?但我什至不知道如何遍历行。

const $ = Cheerio.load(html);
const third = $($("table").get(2));
third.find("tr").each((i, e) => {
  console.log(String(i));
})

这不会产生任何输出。

如果我记录third.html(),它会写入正确表的 html。但我什至无法计算其中的行数,更不用说深入到表格单元格了。我查看了severalother 的答案,但它们都基于根中的单个选择器。我真的不明白third 是什么数据类型,或者如何操作它。

【问题讨论】:

  • 请看this
  • 编辑帖子添加骨架html。
  • 对我来说似乎工作正常。正如预期的那样,输出是单个0

标签: jquery cheerio


【解决方案1】:

Cheerio 的工作方式(或多或少)与 jQuery 相同。因此,如果您不确定如何在 Cheerio 中做某事,我建议您查看 jQuery 文档。无论如何:试试这个:

$('table').eq(2).find("tr").each(function(i, row){
    console.log($(this).find('td').eq(0).html());
    console.log($(this).find('td').eq(2).html())
    console.log($(this).find('td').eq(4).html())
});

【讨论】:

  • 我也没有从 jQuery 文档中理解它。但这有效:)
猜你喜欢
  • 2016-07-23
  • 2023-03-03
  • 2011-02-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-06-13
  • 2013-09-28
  • 1970-01-01
相关资源
最近更新 更多