内容简介:最近在做一个小程序项目,需要爬取第三方数据,于是开始重捡起来爬虫,其实前端爬虫挺好实现的,但因为现在网页出现了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》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!
猜你喜欢:- 前端爬虫攻防之接口签名方案
- 前端使用puppeteer 爬虫生成《React.js 小书》PDF并合并
- 爬虫需谨慎,那些你不知道的爬虫与反爬虫套路!
- 反爬虫之字体反爬虫
- 反爬虫之字体反爬虫
- python网络爬虫之初始网络爬虫
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。