问题描述
有没有办法使用包含一些 html 标签的 Cheerio 从 html 输出文本?我知道 .html()
输出完整的 html,但我只想要使用 .text()
但带有所有 H 标记和中断的文本?
示例:
<div class="className"><h1>Something here</h1></br><p>Next line text</p></div>
应该输出:
<h1>Something here</h1></br>Next line text
编码我现在拥有的:
const $ = await fetchHTML(thisEntry.link);
const content = $(`div[class='${FeedDiv}']`).text()
它只输出 div 的文本,没有任何 alinea 中断或 H1 标签。 .text()
默认也输出 <img>
标签。
更新 我正在尝试执行评论中讨论的修剪功能,但仍然无法正常工作......我是否忽略了什么?
async function fetchHTML(url) {
const { data } = await axios.get(url);
return cheerio.load(data,{ decodeEntities: false });
}
async function createFeed(FeedConfig,entries) {
const $ = await fetchHTML(thisEntry.link);
$(function () {
function clean(o,h) {
var results = '';
if (h == undefined) {
results = o.text().trim();
} else {
$(o)
.children()
.each(function (i,el) {
if (h.indexOf($(el).prop('nodeName').toLowerCase()) >= 0) {
console.log('Found',$(el).prop('nodeName'));
results += $(el).prop('outerHTML');
} else {
console.log($(el).text().trim());
results += $(el).text().trim();
}
});
}
return results;
}
$(".className").html(clean($(".className"),["h1","br"]));
});
console.log($.text().trim());
}
控制台什么都不输出
解决方法
您可以制作自己的修剪样式功能。输入要保留的对象和元素。
示例:
$(function() {
function clean(o,h) {
var results = "";
if (h == undefined) {
results = o.text().trim();
} else {
$(o).children().each(function(i,el) {
if (h.indexOf($(el).prop("nodeName").toLowerCase()) >= 0) {
console.log("Found",$(el).prop("nodeName"));
results += $(el).prop("outerHTML");
} else {
console.log($(el).text().trim());
results += $(el).text().trim();
}
});
}
return results;
}
$(".className").html(clean($(".className"),["h1","br"]));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="className">
<h1>Something here</h1>
</br>
<p>Next line text</p>
</div>
这里有一个陷阱,如果有原始文本,它也可能会被删除。