WEB前端开发人员交流社区

搜索
查看: 1774|回复: 0

Node写的一个爬取网页结构的小蜘蛛

[复制链接]

94

主题

150

帖子

148

积分

管理员

会在前端的道路上一直走下去!

Rank: 15Rank: 15Rank: 15Rank: 15Rank: 15

积分
148

社区QQ达人

发表于 2016-4-4 20:09:25 | 显示全部楼层 |阅读模式
代码中使用了 cheerio 模块,请先安装cheerio 模块, 进入到项目中,运行 nppm install cheerio 即可安装!
这是运行截图:

[JavaScript] 纯文本查看 复制代码
var http = require('http');
var cheerio = require('cheerio');
var url = 'http://bbs.fedte.cc/forum.php';

function filterChapters(html){
        var $ =cheerio.load(html)
        var chapters = $('.xr_forum_box')
        var chapter
        var chapterTitle
        var main
        var chapterMain
        var mainInfo
        var data = []
        chapters.each(function(item){
                chapter = $(this)
                chapterTitle = chapter.find('.xr_forum_tit').find('h2').text()
                main = chapter.find('td')
                chapterMain={
                        title:chapterTitle,
                        main:[]
                }
                main.each(function(item){
                        mainInfo = $(this).find('a').text()
                        chapterMain.main.push(mainInfo)
                })
                
                data.push(chapterMain)
        })
        return data
}
function printCourseInfo(coursDate){
        coursDate.forEach(function(item){
                console.log(item.title + '\n')
                item.main.forEach(function(main){
                        console.log('  '+ main + '\n')
                })
        })
}
http.get(url,function(res){
        var html = '';
        
        res.on('data',function(data){
                html+=data;
        })

        res.on('end',function(){
                //console.log(html)
                var coursDate = filterChapters(html)
                //console.log(coursDate)
                printCourseInfo(coursDate)
        })
}).on('error',function(){
        console.log('获取出错!')
})

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有帐号?立即注册

x
WEB前端开发人员共同的技术交流平台,提倡开源、安全、自由、共享的网络精神! —— —— www.fedte.cn
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则



Archiver|手机版|小黑屋|前端开发技术交流

Copyright © 2009-2015 前端开发技术交流 http://www.fedte.cn 版权所有 All Rights Reserved.

免责声明: 本社区不承担任何由社区会员所提供的信息和工具所引起的争议和法律责任。

GMT+8, 2023-9-22 18:30

快速回复 返回顶部 返回列表