首页 > 解决方案 > 关于表遍历的cheerio node js问题

问题描述

我有一个简单的代码

<div id="details" class="card-detail">
    <table class="card-detail-table">
        <tbody>
            <tr class="first">
                <th>card name</th>
                <td colspan="3">card name testing<br><span class="kana">this is not needed</span></td>
            </tr>
            <tr>
                <th>code</th>
                <td>O3/342</td>
                <th>rarity</th>
                <td>R</td>
            </tr>
        </tbody>
    </table>
</div>

使用cheerio,我想从该表中提取 2 项。

1)我想从只有“卡名测试”的thtd列中获取卡名并忽略“不需要”

2)对于th带有代码和稀有性的东西,我也想获得它们的td价值。

在cheerio中有什么方法可以找到th诸如“代码”或“稀有度”之类的名称并继续td从那里获取下一个值?

标签: javascriptnode.jscheerio

解决方案


香草 JavaScript

使用 vanilla JavaScript,您可以使用以下代码:

  • 找到每个th元素

  • 过滤掉不包含字符串的所有内容'code'

  • 定位nextElementSibling(在本例中为以下td元素),并返回其innerText

[...document.querySelectorAll('th')]
  .filter(el => el.innerText.includes('code'))
  .map(el => el.nextElementSibling.innerText);

Cheerio / JQuery

对于 Cheerio 的 JQuery 风格的语法,我相信等效的是:

$('th')
  .filter(el => el.innerText.includes('code'))
  .map(el => el.nextElementSibling.innerText);

要获得稀有性,只需将'code'上面替换为'rarity'.

--

至于卡名,如果它始终是 的子级<tr class="first">,那么您可以使用它$('tr.first th')来选择正确的元素。


推荐阅读