Home > Web Front-end > JS Tutorial > body text

A brief analysis on the usage of nodejs' HTML analysis tool node-jquery

高洛峰
Release: 2016-12-07 14:09:10
Original
1409 people have browsed it

本文实例分析了nodejs的HTML分析利器node-jquery用法。分享给大家供大家参考,具体如下:

首先描述产生这篇随笔的场景:我需要获取项目在jenkins构建的最新Javascript Coverage显示在供管理层次查看的项目情况Report上,但是由于jenkins没有直接的API取得数据所需数据,所以我们只能从自建的容器发布Javascript Coverage数据API,供Report项目使用。

由于采用简单的数据分析,只是Host一个简单的web Server,所以本人不喜欢Tomcat,IIS这类大型工具,显得有点杀鸡用牛刀,班门弄斧。我更喜欢node.js这类简易的web容器。所以项目采用node.js,并node.js天然的javascript与html操作的天然一体,借助DOM结构使得解析Html更容易,简洁。

Node.js解析HTML DOM的当然是htmlpaser,jsdom。然而个人更喜欢jQuery的风格,与web jQuery的统一API,所以选择了node-jquery.其代码部署在Github的https://github.com/coolaj86/node-jquery.

下面是本人写个一个简单demo:  抓取Github Popular project打印在控制台输出。

var $ = require('jquery');
String.format = function() {
  var s = arguments[0];
  for (var i = 0; i < arguments.length - 1; i++) {
    var reg = new RegExp("\\{" + i + "\\}", "gm");
    s = s.replace(reg, arguments[i + 1]);
  }
  return s;
};
 $.get("https://github.com/popular/forked",function(html){
    var $doc = $(html);
  console.log("No. name language star  forks ")
    $doc.find("ul.repolist li.source").each(function(i,project){
    var $project = $(project);
        var name = $project.find("h3").text().trim();
        var language = $project.find("li:eq(0)").text().trim();
        var star = $project.find("li.stargazers").text().trim();
        var forks = $project.find("li.forks").text().trim();
        var row =String.format("{4} {0} {1} {2} {3}",name,
            language,star,forks,i + 1 );
        console.log(row);
    });
 });
Copy after login


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template