前端爬虫cheerio&&puppeteer

栏目: Node.js · 发布时间: 4年前

内容简介:最近在做一个小程序项目,需要爬取第三方数据,于是开始重捡起来爬虫,其实前端爬虫挺好实现的,但因为现在网页出现了SPA,于是开始疯狂踩坑,聊记此文,以慰诸君。挺简单的,一个工具包,几行代码就解决了但。。。但是,上面例子爬取掘金是不行的,因为掘金就是经典的SPA,服务器只返回一个空的挂载节点,毫无数据。于是引出无头浏览器puppeteer

最近在做一个小程序项目,需要爬取第三方数据,于是开始重捡起来爬虫,其实前端爬虫挺好实现的,但因为现在网页出现了SPA,于是开始疯狂踩坑,聊记此文,以慰诸君。

普通网站爬取数据--cheerio

挺简单的,一个 工具 包,几行代码就解决了

const $ = require('cheerio')
const requestPromise = require('request-promise')
const url = 'https://juejin.im/books';
requestPromise(url)
    .then((html) => {
        // 利用 cheerio 来分析网页内容,拿到所有小册子的描述
        const books = $('.info', html)
        let totalSold = 0
        let totalSale = 0
        let totalBooks = books.length
        // 遍历册子节点,分别统计它的购买人数,和销售额总和
        books.each(function () {
            const book = $(this)
            const price = $(book.find('.price-text')).text().replace('¥', '')
            const count = book.find('.message').last().find('span').text().split('人')[0]
            totalSale += Number(price) * Number(count)
            totalSold += Number(count)
        })

        // 最后打印出来
        console.log(
            `共 ${totalBooks} 本小册子`,
            `共 ${totalSold} 人次购买`,
            `约 ${Math.round(totalSale / 10000)} 万`
        )

    })
复制代码

但。。。但是,上面例子爬取掘金是不行的,因为掘金就是经典的SPA,服务器只返回一个空的挂载节点,毫无数据。于是引出无头浏览器puppeteer

SPA页面爬取--puppeteer

const $ = require('cheerio');
const puppeteer = require('puppeteer');
const url = 'https://juejin.im/books';

async function run(params) {
    //打开一个浏览器
    const browser = await puppeteer.launch();
    // 打开一个页面
    const page = await browser.newPage();
    await page.goto(url, {
        waitUntil: 'networkidle0'
    });
    const html = await page.content();
    const books = $('.info', html);
    let totalSold = 0
    let totalSale = 0
    let totalBooks = books.length
    // 遍历册子节点,分别统计它的购买人数,和销售额总和
    books.each(function () {
        const book = $(this)
        const price = $(book.find('.price-text')).text().replace('¥', '')
        const count = book.find('.message').last().find('span').text().split('人')[0]
        totalSale += Number(price) * Number(count)
        totalSold += Number(count)
    })

    // 最后打印出来
    console.log(
        `共 ${totalBooks} 本小册子`,
        `共 ${totalSold} 人次购买`,
        `约 ${Math.round(totalSale / 10000)} 万`
    )

}
run()
复制代码

以上所述就是小编给大家介绍的《前端爬虫cheerio&&puppeteer》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

四维人类

四维人类

(英)劳伦斯·斯科特 / 祝锦杰 / 浙江教育出版社 / 2018-10 / 79.90元

数字技术如何重新定义 我们的思维方式与生存方式?一起来看看 《四维人类》 这本书的介绍吧!

随机密码生成器
随机密码生成器

多种字符组合密码

Base64 编码/解码
Base64 编码/解码

Base64 编码/解码

RGB HSV 转换
RGB HSV 转换

RGB HSV 互转工具