我需要将一个标记更改为具有相同属性的另一个标记。例如,更改如下:
<TagOne width="500" height="200">asdfasdf</TagOne>
对此:
<AnotherTag width="500" height="200">sometext</AnotherTag>
通过这段代码,我可以看到属性,但我不知道如何将标签替换为另一个:
const htmlparser2 = require("htmlparser2");
const DomUtils = require("htmlparser2").DomUtils;
const htmlContent = `<html>
<head></head> <body> <div id="content">
<TagOne width="500" height="200" src="image1.jpg">asdfasdf</TagOne>
<p>asdfasdf</p> </div></body></html>`; const parser = new htmlparser2.Parser(
{
onopentag(name, attribs) {
if (name === "TagOne") {
if(attribs.width ){
var width = attribs.width;
}
if(attribs.height ){
var height = attribs.height;
}
var new_tag = `<AnotherTag width:`+width+`; height:`+height+`;">sometext</div>`;
}
},
ontext(text) {
console.log("-->", text);
},
onclosetag(tagname,new_tag) {
if (tagname === "amp-iframe") {
console.log("That's it?!");
}
},
},
{ decodeEntities: true } );
var content = parser.write(htmlContent);
parser.end();
我尝试在onclosetag函数上这样做:
//htmlparser2.DomUtils.removeElement(tagname);
//parser.write(new_tag);
但是它给了我一个错误,这不是正确的方法,但是我在文档中找不到任何类似的东西。有人能帮帮我吗?谢谢
1条答案
按热度按时间kkbh8khc1#
试试这个网站,也许能帮到你。[blog]:https://techsparx.com/nodejs/web/htmlparser2.html这个网站描述了如何用htmlparser2替换nodejs中的html