美文网首页
Node实现一个小爬虫

Node实现一个小爬虫

作者: 一蓑烟雨任平生_cui | 来源:发表于2018-10-23 18:11 被阅读0次

以前听到爬虫两个字就瑟瑟发抖,感觉很高大上,多次想一探究竟,最终都被各种原因或事搁置了,总感觉知识储备还没达到。这次较系统的学了Node之后,决定用Node尝试一下。

理论上所有网站都可以爬,无非就是把网站上的内容扒下来,然后提炼自己需要的数据,那怎么提炼?实际上网站上的内容都有特定的结构和样式,根据特定的标签、class、id等解析出来。

以Boss直聘前端列表页为例:

需要用到两个第三方库:
superagent(http://visionmedia.github.io/superagent/ ) 是个 http 库,可以发起 get 或 post 请求。
cheerio(https://github.com/cheeriojs/cheerio ) 类似于 运行在Node中的jquery,可以通过选择器解析爬到的页面特定内容。

const http = require('http');
const cheerio = require('cheerio');
const superagent  = require('superagent');

const server = http.createServer();

server.on('request', (req, res) => {
    superagent.get('https://www.zhipin.com/job_detail/?query=%E5%89%8D%E7%AB%AF&scity=101010100&industry=&position=')
    .end((err, data) => {
        if (err) throw err;

        // data为爬取到的网站内容
        // 将内容转换为可操作的 html 节点
        let $ = cheerio.load(data.text);
        let list = [];

        $("#main .job-list ul li").each((index, element) => {
            let compony = $($(`${element.name} .job-primary .info-primary p`)[index]).text();
            let price = $($(`${element.name} .job-primary .info-primary .name a .red`)[index]).text();
            let title = $($(`${element.name} .info-company .name a`)[index]).text();

            let obj = {
                compony,
                title,
                price
            }

            list.push(obj)
        });

        res.setHeader('Content-Type', 'application/json; charset=UTF-8')

        res.end(JSON.stringify(list))
    })
})

server.listen(3000, (err) => {
    if (err) throw err;
    console.log('runing...')
})

相关文章

网友评论

      本文标题:Node实现一个小爬虫

      本文链接:https://www.haomeiwen.com/subject/ckwazftx.html