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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 14:25:33  来源:igfitidea点击:

JSDOM in nodeJS: How do I get back the manipulated html?

javascriptnode.jsjsdom

提问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

From the jsdom readme:

来自 jsdom 自述文件

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;