Blog

Blog

PHODAL

jsdom 用node解析html

再次用Nodejs构建一个API,这时需要去parse html,找了很久没有找到一个好的库,这时看到了jsdom——关键是可以用jQuery。

jsdom

A JavaScript implementation of the WHATWG DOM and HTML standards.

install

$ npm install jsdom

示例

官网给了下面的一个例子:

var jsdom = require("jsdom");

jsdom.env(
  "http://nodejs.org/dist/",
  ["http://code.jquery.com/jquery.js"],
  function (errors, window) {
    console.log("there have been", window.$("a").length, "nodejs releases!");
  }
);

实战

这里的jquery还需要去下载,感觉会消耗一定的时间,于是参考了官网的例子,用了本地的文件,自己的代码大致如下:

jsdom.env({
    url: "http://example.com/" + name,
    src: [jquery],
    done: function (errors, window) {
        var $ = window.$;
        var result = [];

        csdn_support.prototype.add_blog_info($, result);
        csdn_support.prototype.add_blog_category($, result);
        csdn_support.prototype.add_articles($, result);

        callback(result);
    }
});

这样我们就可以去获取我们想要的结果。

问题是上面的库,就是调用了jQuery去解析HTML,大概就是因为node没有UI?

jsdom信赖库

于是看了看jsdom的依赖库

  • browser-request : Browser port of the Node.js 'request' package
  • contextify: Turn an object into a persistent execution context.
  • cssstyle: CSS StyleDeclaration Object Model implementation
  • htmlparser2: Fast & forgiving HTML/XML/RSS parser
  • nwmatcher: A CSS3-compliant JavaScript selector engine.
  • parse5: WHATWG HTML5 specification-compliant, fast and ready for production HTML parsing/serialization toolset for Node.
  • request: Simplified HTTP request client.
  • xmlhttprequest: XMLHttpRequest for Node
  • browser-request: Browser port of the Node.js 'request' package

原理


或许您还需要下面的文章:

关于我

Github: @phodal     微博:@phodal     知乎:@phodal    

微信公众号(Phodal)

围观我的Github Idea墙, 也许,你会遇到心仪的项目

QQ技术交流群: 321689806
comment

Feeds

RSS / Atom

最近文章

关于作者

Phodal Huang

Engineer, Consultant, Writer, Designer

ThoughtWorks 技术专家

工程师 / 咨询师 / 作家 / 设计学徒

开源深度爱好者

出版有《前端架构:从入门到微前端》、《自己动手设计物联网》、《全栈应用开发:精益实践》

联系我: h@phodal.com

微信公众号: 最新技术分享

标签