javascript - 用 Cheerio 替换 HTML 节点
问题描述
我正在使用Cheerio JS来简化一些古老的 HTML 代码并将其转换为 HTML5。除其他外,我正在替换一些如下所示的重标记引号:
要替换的节点:
<div style="margin:20px; margin-top:5px; ">
<div class="smallfont" style="margin-bottom:2px">Quote:</div>
<table cellpadding="6" cellspacing="0" border="0" width="100%">
<tbody>
<tr>
<td class="alt2" style="border:1px solid #999">
<div>
Originally Posted by <strong>Username</strong>
</div>
<div style="font-style:italic">Lorem ipsum dolor sit amet</div>
</td>
</tr>
</tbody>
</table>
</div>
转换后的输出应该如下所示:
<blockquote>Lorem ipsum dolor sit amet</blockquote>
这是我目前使用的代码当前代码:
$(`table[id^='post']`).each( (i, el) => {
// Get the post
let postBody = $(el).find(`div[id^='post_message_']`).html().trim();
// Replace quotes with blockquotes
cheerio.load(postBody)('div[style^="margin:20px; margin-top:5px; "]').each( (i, el) => {
if ($(el).html().trim().startsWith('<div class="smallfont" style="margin-bottom:2px">Quote')) {
let tbody = $(el).find('tbody > tr > td').html();
let quote = $(el).find('tbody > tr > td > div');
if (quote.html() && quote.text().trim().startsWith('Originally Posted by')) {
let replacement = $('<blockquote>Hello</blockquote>');
quote.parent().html().replace(quote.html(), replacement);
}
// Looks all good
console.log($(el).html())
}
postBody = $(el).html();
});
});
最后,一些上下文的更多 HTML:
<div id="post_message_123456">
As Username has previously written
<br>
<div style="margin:20px; margin-top:5px; ">
<div class="smallfont" style="margin-bottom:2px">Quote:</div>
<table cellpadding="6" cellspacing="0" border="0" width="100%">
<tbody>
<tr>
<td class="alt2" style="border:1px solid #999">
<div>
Originally Posted by <strong>Username</strong>
</div>
<div style="font-style:italic">Lorem ipsum dolor sit amet</div>
</td>
</tr>
</tbody>
</table>
</div>
<br>
I think he has a point!
<img src="smile-with-sunglasses.gif" />
</div>
替换本身似乎有效,console.log()
语句的输出看起来都很好。问题出在最后一行,我试图用替换替换原始内容。不过,postBody
好像以前一样。我究竟做错了什么?
解决方案
试试这样:
let $ = cheerio.load(html)
$('.alt2 div:contains("Originally Posted by")').replaceWith('<blockquote>Lorem ipsum dolor sit amet</blockquote>')
console.log($.html())
推荐阅读
- javascript - 显示 JSON 数据的把手
- php - 什么是 wordpress 核心文件,为什么不应该编辑它们?
- r - 使用 ifelse 将 NA 映射到未知
- objective-c - Core Data Save 返回 False,但 Error 为零
- python - 使用远程 jupyter notebook 时导入模块问题
- java - 将 Docker 和 docker compose 与 Spring Boot REST 应用程序一起使用
- c - 我可以确定该类型是否是 C 中的指针类型吗?
- networking - Chrome 中的旧主机地址
- regex - Pyspark 从日期层次结构存储中读取选定的日期文件
- android - 引用稍后在 android 布局文件中定义的视图是否是一个好习惯