node.js 爬虫

秦小麟IP属地: 陕西
字数 122

pc.js 代码

var http=require ("http");
var url="http://sports.sina.com.cn/nba/1.shtml";
 http.get(url,(res)=>{

     var html="";
     res.on("data",function (chunk) {
         html+=chunk;
     });
     res.on("end",function () {
         console.log(html);
     });
 //    后台返回的数据,携带chunk数据
 }).on("error",(e)=>{
     console.log(e.message);
 //    如果在访问过程中有错误,输出错误信息
 });

爬取 新浪nba球明星
运行:
node pc.js
只能爬出来 网页的源代码
此处需要一个npm 库
cheerio

这是一个用正则来筛选信息的库

npm install cheerio
pc1.js 代码

var http=require ("http");
var cheerio=require("cheerio");
var url="http://sports.sina.com.cn/nba/1.shtml";
 http.get(url,(res)=>{

     var html="";
     res.on("data",function (chunk) {
         html+=chunk;
     });
     res.on("end",function () {
         // console.log(html);
         var $=cheerio.load(html);
         console.log($("#right a").html());
         $("#right a").each(function () {
             console.log($(this).attr("href"));
         });
     });
 //    后台返回的数据,携带chunk数据
 }).on("error",(e)=>{
     console.log(e.message);
 //    如果在访问过程中有错误,输出错误信息
 });

运行:
node pc.js

能获取到网页的href标签内容

pc2.js

var http=require ("http");
var cheerio=require("cheerio");
var fs=require("fs");
var url="http://sports.sina.com.cn/nba/1.shtml";

function httpGet(url,cb) {
    var html="";
    http.get(url,function (res) {
        res.on("data",function (chunk) {
            html+=chunk;
        });
        res.on("end",function () {
            cb(html);
        })
    }).on("error",function (e) {
        console.log(e.message);
    });
    return html;
}
httpGet(url,function (html) {
    var $=cheerio.load(html);
    $("#right a").each(function (index) {
        var newUrl=$(this).attr("href");
        httpGet(newUrl,function (body) {
            var jq=cheerio.load(body);
            fs.writeFile(`./news/${index}.txt`,jq("#artibody").text(),function (err) {
                //用node.js 把获取到的text放入一个news文件夹
                if(err){
                    return console.log(err.message);
                }
                console.log("完成");
            })
        })

    })

});

运行:
node pc.js

一个封装好的httpGet函数 并且用 node.js 里边的 fs.writeFile函数 将获取到的数据 放在一个new的文件夹中

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
7人点赞
秦小麟顶亲亲的IT程序媛~
总资产100共写了4309字获得554个赞共177个粉丝

推荐阅读更多精彩内容

  • 你可能会把 NodeJS 用作网络服务器,但你知道它还可以用来做爬虫吗? 本教程中会介绍如何爬取静态网页——还有那...
    张嘉夫阅读 5,126评论 3 51
  • 前言:最近想学习node.js,突然在网上看到基于node的爬虫制作教程,所以简单学习了一下,把这篇文章分享给同样...
    京东内部优惠券阅读 1,403评论 0 12
  • 一、准备阶段 当我们需要使用Node.js进行爬虫爬取网页时,我们通常需要下载两个库request和cheerio...
    Srtian阅读 186评论 0 0
  • 一、项目描述 引言:在电影天堂下电视剧的下伙伴有木有发现,它没有提供批量下载功能,美剧英剧还好,10集左右,我就多...
    danieldai阅读 5,358评论 8 19
  • 我的2017—— 那些悲伤和思念难以告别 那些奇葩的事情啼笑皆非 那些老去的时光无力的呻吟 那些稚嫩的笑声是上天的...
    蓟门闲客阅读 131评论 0 0