前言
最近在做一个小程序项目,需要爬取第三方数据,于是开始重捡起来爬虫,其实前端爬虫挺好实现的,但因为现在网页出现了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()
- 复制代码