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

点点圈 提交于 2019-11-29 13:10:30

问题


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?

  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();

        }
    });

回答1:


From the jsdom readme:

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().




回答2:


sometimes jQuery isn't the answer

content = window.document.documentElement.outerHTML;


来源:https://stackoverflow.com/questions/31828568/jsdom-in-nodejs-how-do-i-get-back-the-manipulated-html

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!