• Node.js 解析gzip网页(https)


    gzip网页指网页头字段Content-Encoding是gzip(GNU zip)内容编码方式。内容编码是指不丢失实体信息的前提下所进行的压缩。

    Node.js 代码如下:

    //====================================================
    // 访问www.meitulu.com得到pagecode
    // 2017年11月6日
    //====================================================
    
    
    // 内置https模块,提供了https服务器和客户端功能
    var https=require("https");
    
    var zlib = require('zlib'); 
    
    // cheerio模块,提供了类似jQuery的功能
    var cheerio = require("cheerio");
    
    // 内置文件处理模块
    var fs=require('fs');
    
    // 请求参数JSON
    var options;
    
    // request请求
    var req;
    
    //--------------------------------------
    // 程序入口 Accept-Encoding:gzip, deflate, br
    //--------------------------------------
    function start(){
        // 初始化options  
        options={
            hostname:'www.meitulu.com',
                port:443,
                path:'/item/40.html',// 子路径
              method:'GET',
               agent:false,
                gzip: true,
        };
    
        
        req=https.request(options,function(resp){
            var html = [];
    
            resp.on("data", function(data) {
                html.push(data);
            })
            resp.on("end", function() {
                var buffer = Buffer.concat(html);
                zlib.gunzip(buffer, function(err, decoded) {
                    console.log(decoded.toString());// gzip解压后的html文本
    
                    
                })
            }).on("error", function() {
                console.log("获取失败")
            })
        });
    
        // 超时处理
        req.setTimeout(5000,function(){
            req.abort();
        });
    
        // 出错处理
        req.on('error',function(err){
            if(err.code=="ECONNRESET"){
                console.log('socket端口连接超时。');
            }else{
                console.log('请求发生错误,err.code:'+err.code);
            }
        });
    
        // 请求结束
        req.end();
    }
    
    // 调用start函数,程序开始
    start();

    参考文档:

    http://blog.csdn.net/u012935179/article/details/74022000

  • 相关阅读:
    增强学习笔记 第二章 多臂赌博机问题
    学习计划与目标
    2020秋季新学期
    2019春总结作业
    2019春年第四次课程设计实验报告
    2019春年第三次课程设计实验报告
    2019春年第二次课程设计实验报告
    2019春年第一次课程设计实验报告
    2019春第十二周作业
    2019春第十一周作业
  • 原文地址:https://www.cnblogs.com/heyang78/p/7791465.html
Copyright © 2020-2023  润新知