【Nodejs】cheerio简单示例
cheerio的API挺多,我也了解有限,欲知详情请参考 “通读cheerio API”。
下面就事论事聊聊它的基本使用。
比如说在某网页中有这么一段HTML:
</tbody> <tbody id="stickthread_8349137" class="bs_bg1" > <tr> <td class="icon"> <a href="chat.php?tid=8349137" title="聊天模式" target="_blank"><img src="images/icons/icon6.gif" alt="Icon15" class="icon" /></a> </td> <th class="hot" > <label> <img src="images/2008/pin_1.gif" alt="本版置顶" title="本版置顶"/> </label> <em>[<a href="forumdisplay.php?fid=8&filter=type&typeid=48">看盘</a>]</em> <span id="thread_8349137" class="forumdisplay"><a href="thread-8349137-1-1.html" style="font-weight: bold;color: hotpink" target="_blank"> 2018年4月25日实时看盘交流 </a></span> <img src="images/attachicons/common.gif" alt="附件" title="附件" class="attach" /> <span class="threadpages"> <a href="thread-8349137-2-1.html">2</a> <a href="thread-8349137-3-1.html">3</a> <a href="thread-8349137-4-1.html">4</a> <a href="thread-8349137-5-1.html">5</a> <a href="thread-8349137-6-1.html">6</a> .. <a href="thread-8349137-14-1.html">14</a> </span> </th> <td class="author"> <cite> <a href="space.php?action=viewpro&uid=2713715">美人鱼苗苗</a> </cite> <em class="ad_hong" >2018-4-24</em> </td> <td class="nums"><strong>267</strong><em>4911</em></td> <td class="lastpost"> <cite><a href="space.php?action=viewpro&username=%D6%F1%D4%B0%C7%E5">竹园清</a></cite> <em><a href="redirect.php?tid=8349137&goto=lastpost#lastpost"><font class="ad_hong">今天 20:33</font></a></em> </td> </tr> </tbody>
注意上面代码中加粗加下划线的三个部分,它们是:
thread-8349137-1-1.html
2018年4月25日实时看盘交流
14
这三个量分别对应了帖子的地址,标题和共多少页,如果要用cheerio取到它们该如何呢,请见代码:
var buffer = Buffer.concat(html); var body = iconv.decode(buffer,'gb2312'); var $ = cheerio.load(body); // 这个$是整个网页的dom $("tbody").each(function(index,element){ // 先找到tody节点 var $tbody=cheerio.load($(element).html()); var topic={}; topic.pageCount=1; topic.url=null; topic.title=null; $tbody(".forumdisplay a").each(function(index,element){ // 再找tbody节点里的class=forumdisplay里面的链接 var topicUrl='http://www.55188.com/'+$tbody(element).attr("href"); // 得到链接的属性(第一项) var topicTitle=$tbody(element).text();// 得到链接的文字(第二项) topic.url=topicUrl topic.title=topicTitle; }) $tbody(".threadpages").each(function(index,element){ // 再找tbody节点里的class=threadpages节点 topic.pageCount=$tbody(element).children().last().text();// 找到最后一个子节点的文字(第三项) }) if(topic.url!=null && topic.title!=null){ topics.push(topic); // 加入数组 } })
这样就找到了需要的三个值。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)
2015-04-25 安全驾驶技巧