[英]Getting element name inside html using cheerio
New to front end stuff.前端东西的新手。 I am having trouble getting element inside html using cheerio.我无法使用cheerio 在html 中获取元素。 Please see below what I am trying.请在下面查看我正在尝试的内容。 I looked other posts, they help to understand how cheerio works but not this.我查看了其他帖子,它们有助于了解cheerio 的工作原理,但不是这个。
My goal is to get value ex.我的目标是获得价值。 I want to get value 67% from <td class="ctr2">67%</td>
.我想从<td class="ctr2">67%</td>
获得 67% 的价值。 I am getting undefined.我越来越不确定了。 This tag td class="ctr2"
appears multiple times but I want from first only.这个标签td class="ctr2"
出现多次,但我只想要第一个。
I have been trying for quiet some time now.一段时间以来,我一直在努力保持安静。 I get undefined
using cheerio.我使用cheerio得到undefined
。 What is that I am missing?我错过了什么?
<tfoot>
<tr>
<td>Total</td>
<td class="bar">966 of 2,945</td>
<td class="ctr2">67%</td>
<td class="bar">56 of 168</td>
<td class="ctr2">66%</td>
<td class="ctr1">72</td>
<td class="ctr2">224</td>
<td class="ctr1">167</td>
<td class="ctr2">580</td>
<td class="ctr1">31</td>
<td class="ctr2">140</td>
<td class="ctr1">0</td>
<td class="ctr2">17</td>
</tr>
</tfoot>
I am trying below using cheerio in node.js我正在尝试在 node.js 中使用cheerio
const cheerio = require('cheerio');
var fs = require('fs');
const demo= cheerio.load(fs.readFileSync('sample123.html'))
console.log(demo('#ctr2'));
I see a couple problems with your code:我发现您的代码存在一些问题:
#ctr2
is a selector for an element with id="cntr2"
. #ctr2
是id="cntr2"
元素的选择器。 You don't have any id
values in your HTML.您的 HTML 中没有任何id
值。 Instead, you need to use ".ctr2"
if you want to select items with that class name.相反,如果要选择具有该类名的项目,则需要使用".ctr2"
。<table>
and </table>
surrounding it.您的 HTML 不完整,因为它周围没有<table>
和</table>
。If you fix those two things and run this code:如果您修复这两件事并运行此代码:
const cheerio = require('cheerio');
var fs = require('fs');
const $ = cheerio.load(fs.readFileSync('sample123.html'))
$('.ctr2').each((index, element) => {
console.log($(element).text());
});
Then, it will generate this output:然后,它将生成以下输出:
67%
66%
224
580
140
17
If you only want the first .cntr2
item, you can use .first()
on the selector results like this:如果您只想要第一个.cntr2
项目,您可以在选择器结果上使用.cntr2
.first()
,如下所示:
const cheerio = require('cheerio');
var fs = require('fs');
const $ = cheerio.load(fs.readFileSync('sample123.html'))
console.log($('.ctr2').first().text());
Which will generate this output:这将生成此输出:
67%
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.