如何从html源创建document
对象并在node.js中使用document.*
等getElementById
函数?
答案 0 :(得分:11)
您可能需要类似DOM的javascript实现,jsdom。
答案 1 :(得分:4)
如果您只是想使用类似jQuery的API来遍历和摆弄HTML标记,那么更好的选择是cheerio。
jsdom是一个成熟的DOM实现,甚至可以运行页面附带的JS。结果,它非常沉重。如果你不需要任何这些功能,那么cheerio会快8倍。
var cheerio = require('cheerio'),
$ = cheerio.load('<h2 class="title">Hello world</h2>');
$('h2.title').text('Hello there!');
$('h2').addClass('welcome');
$.html();
//=> <h2 class="title welcome">Hello there!</h2>