最近在作一个小程序项目,须要爬取第三方数据,因而开始重捡起来爬虫,其实前端爬虫挺好实现的,但由于如今网页出现了SPA,因而开始疯狂踩坑,聊记此文,以慰诸君。html
挺简单的,一个工具包,几行代码就解决了前端
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小程序
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()
复制代码