如何使用Cheerio js删除<div>和<br>?

我有以下的html,我喜欢通过Cheeriosparsing。

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()) 

我的最终目标是尝试parsinghtml

  • 删除所有的div
  • 清理<br clear="none"/>并更改为<br>
  • 最后把所有空的“元素”(带有“div”的句子)去掉,加上'p'句子'/ p'

我试着从上面写的代码中以较小的目标开始。 我试图删除所有'div'(这是成功的),但我无法find'br'。 我一直在尝试几天,没有头。

所以我写在这里寻求一些帮助和暗示,我怎样才能达到我的最终目标。

谢谢:D

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

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

并为每个div,你检查是否有一个<br>标签

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

如果是,则删除该属性

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

如果不是,则创build一个具有相同内容的P

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

然后用PreplaceDIV

 $(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()); 

你不想删除一个属性,你想删除标签,所以你想切换removeAttr remove ,如下所示:

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