gpt4 book ai didi

javascript - 如何使用 Cheerio js 删除

转载 作者:数据小太阳 更新时间:2023-10-29 05:12:17 26 4
gpt4 key购买 nike

我有以下 html,我想通过 Cheerios 进行解析。

    var $ = cheerio.load('<html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/></head><body style="word-wrap: break-word; -webkit-nbsp-mode: space; -webkit-line-break: after-white-space;"><div>This works well.</div><div><br clear="none"/></div><div>So I have been doing this for several hours. How come the space does not split? Thinking that this could be an issue.</div><div>Testing next paragraph.</div><div><br clear="none"/></div><div>Im testing with another post. This post should work.</div><div><br clear="none"/></div><h1>This is for test server.</h1></body></html>', {
normalizeWhitespace: true,
});

// trying to parse the html
// the goals are to
// 1. remove all the 'div'
// 2. clean up <br clear="none"/> into <br>
// 3. Have all the new 'empty' element added with 'p'

var testData = $('div').map(function(i, elem) {
var test = $(elem)
if ($(elem).has('br')) {
console.log('spaceme');
var test2 = $(elem).removeAttr('br');
} else {
var test2 = $(elem).removeAttr('div').add('p');
}
console.log(i +' '+ test2.html());
return test2.html()
})

res.send(test2.html())

我的最终目标是尝试解析 html

  • 删除所有的div
  • 清理 <br clear="none"/>并更改为 <br>
  • 最后删除所有空“元素”(那些带有“div”的句子)以添加“p”句子“/p”

在我编写的上述代码中,我尝试从一个较小的目标开始。我试图删除所有的“div”(这是成功的)但我无法找到“br”。我已经试了好几天了,没有头绪。

所以我在这里写信是为了寻求一些帮助和提示,以了解如何实现我的最终目标。

谢谢你:D

最佳答案

这比看起来容易,首先你遍历所有 DIV

$('div').each(function() { ...

对于每个 div,你检查它是否有一个 <br>标签

$(this).find('br').length

如果是,则删除该属性

$(this).find('br').removeAttr('clear');

如果不是你创建一个内容相同的P

var p = $('<p>' + $(this).html() + '</p>');

然后只需将 DIV 替换为 P

$(this).replaceWith(p);

和输出

res.send($.html());

一切都是

$('div').each(function() {
if ( $(this).find('br').length ) {
$(this).find('br').removeAttr('clear');
} else {
var p = $('<p>' + $(this).html() + '</p>');
$(this).replaceWith(p);
}
});

res.send($.html());

关于javascript - 如何使用 Cheerio js 删除 <div> 和 <br>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28790458/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com