javascript - 关于表遍历的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)我想从只有“卡名测试”的th
和td
列中获取卡名并忽略“不需要”
2)对于th
带有代码和稀有性的东西,我也想获得它们的td
价值。
在cheerio中有什么方法可以找到th
诸如“代码”或“稀有度”之类的名称并继续td
从那里获取下一个值?
解决方案
香草 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')
来选择正确的元素。