博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
NodeJs+http+fs+request+cheerio 采集,保存数据,并在网页上展示(构建web服务器)
阅读量:7183 次
发布时间:2019-06-29

本文共 2701 字,大约阅读时间需要 9 分钟。

目的:

  数据采集

  写入本地文件备份

  构建web服务器

  将文件读取到网页中进行展示

目录结构:

package.json文件中的内容与上一篇一样:

request : 使得请求变得更容易,简单

cheerio: 用来解析dom结构,类似jQuery,挺好用

app.js文件:

/** * 数据采集 * 写入本地文件备份 * 创建web服务器 * 将文件读取到网页中进行展示 *///引入需要的包var http = require('http');//var path = require('path');var request = require('request');var cheerio = require('cheerio');var fs = require('fs');//定义常量var dolphin = 'http://cn.dolphin.com/blog';const filePath = '/NodeJsTest/test_7/sampleCollection/localFiles/opts.txt';//数据请求function dataRequest(dataUrl) {    //发送请求    request({        url : dataUrl,        method : 'GET'    },function(err, red, body) {        //请求到body        if(err){            console.log(dataUrl);            console.error('[ERROR]Collection' + err);                    return;        }        if(dataUrl && dataUrl === dolphin){            dataPraseDolphin(body);        }    })}/** * 解析html */function dataPraseDolphin(body) {        var $ = cheerio.load(body);    var atricles = $('#content').children('.status-publish');    for(var i = 0;i < atricles.length;i++){        var article = atricles[i];        var $a = $(article).find('.post-title .entry-title a');        var $p = $(article).find('.post-content p');        var $aVal = $($a).text();        var $pVal = $($p).text();        var localData;        if($p){            localData = '--------------'+ (i+1) +' Chapter------------------' + '\n'                      + '标题:' + $aVal + '\n'                      + '简介:' + $pVal + '\n'                      + '时间:' + new  Date + '\n'                      + '---------------------------------------------------' + '\n';            console.log(localData);            writeToLocal(localData,i);        }    }}/** * [writeToLocal description] * 将解析的数据 写入本地文件进行备份 */function writeToLocal(dataPage,fj){    console.log('-------------准备写入文件------------------------')    //同步写入文件,一般使用异步好    fs.appendFileSync(filePath, dataPage);}/** * 创建web服务器 * @return {[type]} [description] */function createServer(){    http.createServer(function(req,resp){        console.log('服务启动!')        wirteToPage(resp);            }).listen(7000);}/** * 将抓取的数据写入页面 */function wirteToPage(resp){    fs.readFile(filePath,function(err,data){        if(err){            console.log(err);            resp.writeHead(404,{                'Content-Type':'text/html'            })        }else{            resp.writeHead(200,{                //响应头添加编码格式解决乱码问题                'Content-Type': 'text/plain;charset=utf-8'            });            //resp.write('
'); resp.write(data.toString()); } resp.end(); })}//开始发送请求 并 采集数据dataRequest(dolphin);createServer();

Sublime 中 ctrl+B 执行 

浏览器地址栏请求:http://localhost:7000

 结果

 

 

转载地址:http://yrukm.baihongyu.com/

你可能感兴趣的文章
通过交换 a,b 中的元素,使[序列 a 元素的和]与[序列 b 元素的和]之间的差最小。...
查看>>
Cesium入门7 - Adding Terrain - 添加地形
查看>>
kubernetets单机版安装
查看>>
MAC-mojave-关于VMware虚拟机键盘鼠标失灵解决
查看>>
我的友情链接
查看>>
2-2 中断/异常机制工作原理
查看>>
Java到底是传引用还是传值?
查看>>
RAR压缩包审计工具unrar-nofree
查看>>
什么是CSS网页切图
查看>>
ConcurrentHashMap学习
查看>>
struts2标签实例
查看>>
Golang walk在win及linux建立 GUI 應用程式
查看>>
Linux执行命令常见的英语语句
查看>>
elasticsearch简单JavaAPI总结
查看>>
线索化二叉树
查看>>
vimrc
查看>>
【Spark亚太研究院系列丛书】Spark实战高手之路-第一章 构建Spark集群(第四步)(1)...
查看>>
Perl语言之统计特定字符串个数
查看>>
Linux用户和组管理
查看>>
Eclipse中从svn上检出项目无法识别jar包
查看>>