再次用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
原理
或许您还需要下面的文章: