zoukankan      html  css  js  c++  java
  • Node.js爬虫网页请求模块

    注:如您下载最新的nodegrass版本,由于部分方法已经更新,本文的例子已经不再适应,详细请查看开源地址中的例子。
    一、为什么我要写这样一个模块?

    源于笔者想使用Node.js写一个爬虫,虽然Node.js官方API提供的请求远程资源的方法已经非常简便,具体参考

    http://nodejs.org/api/http.html 其中对于Http的请求提供了,http.get(options, callback)和http.request(options, callback)两个方法,

    看方法便知,get方法用于get方式的请求,而request方法提供更多的参数,例如其它请求方式,请求主机的端口等等。对于Https的请求于Http类似。一个最简单的例子:

     1 var https = require('https');
     2 
     3 https.get('https://encrypted.google.com/', function(res) {
     4   console.log("statusCode: ", res.statusCode);
     5   console.log("headers: ", res.headers);
     6 
     7   res.on('data', function(d) {
     8     process.stdout.write(d);
     9   });
    10 
    11 }).on('error', function(e) {
    12   console.error(e);
    13 });

    对于以上代码,我们无非就是想请求远程主机,得到响应信息,例如响应状态,响应头,响应主体内容。其中get方法的第二个参数是一个回调函数,我们异步的获取响应信息,然后,在该回调函数中,res对象又监听data,on方法中第二个参数又是一个回调,而你得到d(你请求到的响应信息)后,很可能在对它进行操作的时候再次引入回调,一层层下去,最后就晕了。。。对于异步方式的编程,对于一些习惯同步方式写代码的同学是非常纠结的,当然国内外已经对此提供了一些非常优秀的同步类库,例如老赵的Wind.js......好像有点扯远了。其实,我们调用get最终要得到的无非就是响应信息,而不关心res.on这样的监听过程,因为太懒惰。不想每次都res.on('data',func),于是诞生了今天我要介绍的nodegrass。

    二、nodegrass请求资源,像Jquery的$.get(url,func)

    一个最简单的例子:

    1 var nodegrass = require('nodegrass');
    2 nodegrass.get("http://www.baidu.com",function(data,status,headers){
    3     console.log(status);
    4     console.log(headers);
    5     console.log(data);
    6 },'gbk').on('error', function(e) {
    7     console.log("Got error: " + e.message);
    8 });

    咋一看,和官方原来的get没啥区别,确实差不多=。=!只不过少了一层res.on('data',func)的事件监听回调而已。不管你信不信,反正我看上去感觉舒服多了,第二个参数同样是一个回调函数,其中的参数data是响应主体内容,status是响应状态,headers是响应头。得到响应内容,我们就可以对得到的资源提取任何我们感兴趣的信息啦。当然这个例子中,只是简单的打印的控制台而已。第三个参数是字符编码,目前Node.js不支持gbk,这里nodegrass内部引用了iconv-lite进行了处理,所以,如果你请求的网页编码是gbk的,例如百度。只需加上这个参数就行了。

    那么对于https的请求呢?如果是官方api,你得引入https模块,但是请求的get方法等和http类似,于是nodegrass顺便把他们整合在一块了。看例子:

    1 var nodegrass = require('nodegrass');
    2 nodegrass.get("https://github.com",function(data,status,headers){
    3     console.log(status);
    4     console.log(headers);
    5     console.log(data);
    6 },'utf8').on('error', function(e) {
    7     console.log("Got error: " + e.message);
    8 });

    nodegrass会根据url自动识别是http还是https,当然你的url必须得有,不能只写www.baidu.com/而需要http://www.baidu.com/

    对于post的请求,nodegrass提供了post方法,看例子:

    var ng=require('nodegrass');
    ng.post("https://api.weibo.com/oauth2/access_token",function(data,status,headers){
        var accessToken = JSON.parse(data);
        var err = null;
        if(accessToken.error){
             err = accessToken;
        }
        callback(err,accessToken);
        },headers,options,'utf8');

    以上是新浪微博Auth2.0请求accessToken的一部分,其中使用nodegrass的post请求access_token的api。

    post方法相比get方法多提供了headers请求头参数,options--post的数据,它们都是对象字面量的类型:

     1 var headers = {
     2         'Content-Type': 'application/x-www-form-urlencoded',
     3         'Content-Length':data.length
     4     };
     5 
     6 var options = {
     7              client_id : 'id',
     8          client_secret : 'cs',
     9          grant_type : 'authorization_code',
    10          redirect_uri : 'your callback url',
    11          code: acode
    12     };

    三、利用nodegrass做代理服务器?……**

    看例子:

    var ng = require('nodegrass'),
         http=require('http'),
         url=require('url');

         http.createServer(function(req,res){
            var pathname = url.parse(req.url).pathname;
            
            if(pathname === '/'){
                ng.get('http://www.cnblogs.com/',function(data){
                    res.writeHeader(200,{'Content-Type':'text/html;charset=utf-8'});
                    res.write(data+"\n");
                    res.end();
                    },'utf8');
                }
         }).listen(8088);
         console.log('server listening 8088...');

     就这么简单,当然代理服务器还有复杂的多,这个不算是,但至少你访问本地8088端口,看到的是不是博客园的页面呢?

    nodegrass的开源地址:https://github.com/scottkiss/nodegrass

    作者:Sirk  
    本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。

     
  • 相关阅读:
    mac os programming
    Rejecting Good Engineers?
    Do Undergrads in MIT Struggle to Obtain Good Grades?
    Go to industry?
    LaTex Tricks
    Convert jupyter notebooks to python files
    How to get gradients with respect to the inputs in pytorch
    Uninstall cuda 9.1 and install cuda 8.0
    How to edit codes on the server which runs jupyter notebook using your pc's bwroser
    Leetcode No.94 Binary Tree Inorder Traversal二叉树中序遍历(c++实现)
  • 原文地址:https://www.cnblogs.com/vimsk/p/2697806.html
Copyright © 2011-2022 走看看