前端爬蟲cheerio&&puppeteer

前言

最近在作一個小程序項目,須要爬取第三方數據,因而開始重撿起來爬蟲,其實前端爬蟲挺好實現的,但由於如今網頁出現了SPA,因而開始瘋狂踩坑,聊記此文,以慰諸君。html

普通網站爬取數據--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()
複製代碼

爬取小冊頁面數據以下

相關文章
相關標籤/搜索