javascript nodeJS 中的 JSDOM:如何取回被操纵的 html?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31828568/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JSDOM in nodeJS: How do I get back the manipulated html?
提问by Guy
I am trying to manipulate a remote HTML and return it manipulated. I decided to use JSDOM but cannot figure out how to get the manipulated HTML back. Any ideas?
我正在尝试操作远程 HTML 并将其返回操作。我决定使用 JSDOM,但无法弄清楚如何恢复被操纵的 HTML。有任何想法吗?
jsdom.env({
url: "http://www.cnn.com",
scripts: ["http://code.jquery.com/jquery.js"],
done: function (err, window) {
var $ = window.$;
console.log("HN Links");
var src = $(".ghciTopStoryImage1 img").attr('src','http://lorempixel.com/396/220/');
var headline = $(".blkbigheader span").html('header');
var description = $(".blkbigheader").parent().find("p a:eq(0)").html('text');
// not working....
content =$(window.document).html();
}
});
回答by Domenic
var JSDOM = require("jsdom").JSDOM;
var jsdom = new JSDOM("<!DOCTYPE html>hello");
jsdom.serialize() === "<!DOCTYPE html><html><head></head><body>hello</body></html>";
doc.documentElement.outerHTML === "<html><head></head><body>hello</body></html>";
Adapting your above example would then just be content = jsdom.serialize()
.
调整你上面的例子就可以了content = jsdom.serialize()
。
回答by Jaromanda X
sometimes jQuery isn't the answer
有时 jQuery 不是答案
content = window.document.documentElement.outerHTML;