【问题标题】:JSDOM in nodeJS: How do I get back the manipulated html?nodeJS 中的 JSDOM:如何取回被操纵的 html?
【发布时间】:2015-08-05 09:30:37
【问题描述】:

我正在尝试操作远程 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();

        }
    });

【问题讨论】:

  • 在我使用的类似的东西中:window.document.querySelector( 'html' ).outerHTML 来获取整个文档。

标签: javascript node.js jsdom


【解决方案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>";

调整你上面的例子就是content = jsdom.serialize()

【讨论】:

    【解决方案2】:

    有时 jQuery 不是答案

    content = window.document.documentElement.outerHTML;
    

    【讨论】:

    • 这将剥离文档类型
    • 使用window.document.doctype轻松添加
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-02-07
    • 1970-01-01
    • 2022-11-28
    • 1970-01-01
    • 1970-01-01
    • 2016-09-11
    • 1970-01-01
    相关资源
    最近更新 更多