htmlparser2是一个fast&forgivingHTML/XML解析器。
npminstallhtmlparser2htmlparser2的 livedemo:https://astexplorer.net/#/2AmVrGuGVJ
htmlparser2本身提供了一个回调接口,允许以最小的分配来消耗文档。为了获得更符合人体工程学的体验,可阅读下面的GettingaDOM。
consthtmlparser2=require("htmlparser2");constparser=newhtmlparser2.Parser({onopentag(name,attributes){/**Thisfireswhenanewtagisopened.**Ifyoudon'tneedanaggregated`attributes`object,*havealookatthe`onopentagname`and`onattribute`events.*/if(name==="script"&&attributes.type==="text/javascript"){console.log("JS!Hooray!");}},ontext(text){/**Fireswheneverasectionoftextwasprocessed.**Notethatthiscanfireatanypointwithintextandyoumight*havetostichtogethermultiplepieces.*/console.log("-->",text);},onclosetag(tagname){/**Fireswhenatagisclosed.**Youcanrelyonthiseventonlyfiringwhenyouhavereceivedan*equivalentopeningtagbefore.Closingtagswithoutcorresponding*openingtagswillbeignored.*/if(tagname==="script"){console.log("That'sit?!");}},});parser.write("Xyz<scripttype='text/javascript'>constfoo='<<bar>>';</script>");parser.end();Output(withmultipletexteventscombined):
-->XyzJS!Hooray!-->constfoo='<<bar>>';That'sit?!
评论