做者:William
本文为原创文章,转载请注明做者及出处javascript
Electron 可让你使用纯 JavaScript 调用 Chrome 丰富的原生的接口来创造桌面应用。你能够把它看做一个专一于桌面应用的 Node.js 的变体,而不是 Web 服务器。其基于浏览器的应用方式能够极方便的作各类响应式的交互,接下来介绍下关于 Electron 上衍生出的框架 Nightmare。css
Nightmare 是一个基于 Electron 的框架,针对 Web 自动化测试和爬虫(其实爬虫这个是你们本身给这个框架加的功能XD),由于其具备跟 PlantomJS 同样的自动化测试的功能能够在页面上模拟用户的行为触发一些异步数据加载,也能够跟 Request 库同样直接访问 URL 来抓取数据,而且能够设置页面的延迟时间,因此不管是手动触发脚本仍是行为触发脚本都是垂手可得的(这边注意,若是事件具有 isTrusted 的检查的话,就没法触发了)。html
为了更快速使用 NPM 下载,可使用淘宝的镜像地址。直接 NPM 安装Nightmare 就完成安装了(二进制的 Electron 依赖有点大,安装时间可能比较长)。前端
写一个简单的启动 app.js;java
const Nightmare = require('nightmare') const nightmare = new Nightmare({ show: true, openDevTools: { mode: 'detach' } }) nightmare.goto('https://www.hujiang.com') .evaluate(function() { // 该环境中能使用浏览器中的任何对象window/document,而且返回一个promise console.log('hello nightmare') console.log('5 second close window') }) .wait(5000) .end() .then(()=> { console.log('close nightmare') })
这个脚本会在打开的浏览器的调试控制台中打印出 hello nightmare 而且在5秒后关闭,随后在运行的该脚本的中输出 close nightmare。git
利用了 Electron 提供的 Browser 的环境,同时具有了 Node.js 的 I/O 能力,因此能够很方便实现一个爬虫应用。Nightmare 的官网有更详细的介绍:github
大体操做:chrome
咱们以抓取知乎上的话题的为应用场景,须要的数据是知乎的话题信息 包含如下字段 话题名称/话题的图片/关注者数量/话题数量/精华话题数量,可是由于后三者只能在其父亲话题中包含,因此必须先抓父话题才能抓取子话题,并且这些子话题是以 hover 的形式在父话题中异步加载的,若是用Request/Superagent 须要 HTTP 传递其解析过的id才能获取,可是用Nightmare 能够直接调用其 hover 事件触发数据的加载。json
第一步获取须要抓取的话题深度,默认的根是如今知乎的根话题;promise
/** * 抓取对应的话题页面的url和对应的深度保存到指定的文件名中 * @param {string} rootUrl - 顶层的url * @param {int} deep - 抓取页面的深度 * @param {string} toFile - 保存的文件名 * @param {Function} cb - 完成后的回调 */ async function crawlerTopicsFromRoot (rootUrl, deep, toFile, cb) { rootUrl = rootUrl ||'https://www.zhihu.com/topic/19776749/hot' toFile = toFile || './topicsTree.json' console.time() const result = await interactive .iAllTopics(rootUrl, deep) console.timeEnd() util.writeJSONToFile(result['topics'], toFile, cb) } crawlerTopicsFromRoot('', 2, '', _ => { console.log('完成抓取') })
而后进行交互函数的核心函数,注意在开始抓取前,要去看看知乎的 robots.txt 文件看看哪些能抓和抓取的间隔否则很容易 timeout 的错误。
// 获取对应的话题的信息 const cntObj = queue.shift() const url = `https://www.zhihu.com/topic/${cntObj['id']}/hot` const topicOriginalInfo = await nightmare .goto(url) .wait('.zu-main-sidebar') // 等待该元素的出现 .evaluate(function () { // 获取这块数据 return document.querySelector('.zu-main-sidebar').innerHTML }) // .....若干步的操做后 // 获取其子话题的数值信息 const hoverElement = `a.zm-item-tag[href$='${childTopics[i]['id']}']` const waitElement = `.avatar-link[href$='${childTopics[i]['id']}']` const topicAttached = await nightmare .mouseover(hoverElement) // 触发hover事件 .wait(waitElement) .evaluate(function () { return document.querySelector('.zh-profile-card').innerHTML }) .then(val => { return parseRule.crawlerTopicNumbericalAttr(val) }) .catch(error => { console.error(error) })
cheerio 是一个 jQuery 的 selector 库,能够应用于 HTML 片断而且得到对应的DOM 元素,而后咱们就能够进行对应的 DOM 操做->增删改查均可以,这边主要用来查询 DOM 和获取数据。
const $ = require('cheerio') /** *抓取对应话题的问题数量/精华话题数量/关注者数量 */ const crawlerTopicNumbericalAttr = function (html) { const $ = cheerio.load(html) const keys = ['questions', 'top-answers', 'followers'] const obj = {} obj['avatar'] = $('.Avatar.Avatar--xs').attr('src') keys.forEach(key => { obj[key] = ($(`div.meta a.item[href$=${key}] .value`).text() || '').trim() }) return obj } /** * 抓取话题的信息 */ const crawlerTopics = function (html) { const $ = cheerio.load(html) const obj = {} const childTopics = crawlerAttachTopic($, '.child-topic') obj['desc'] = $('div.zm-editable-content').text() || '' if (childTopics.length > 0) { obj['childTopics'] = childTopics } return obj } /** * 抓取子话题的信息id/名称 */ const crawlerAttachTopic = function ($, selector) { const topicsSet = [] $(selector).find('.zm-item-tag').each((index, elm) => { const self = $(elm) const topic = {} topic['id'] = self.attr('data-token') topic['value'] = self.text().trim() topicsSet.push(topic) }) return topicsSet }
而后一个简单的爬虫就完成了,最终得到部分数据格式如何:
{ "value": "rootValue", "id": "19776749", "fatherId": "-1", "desc": "知乎的所有话题经过父子关系构成一个有根无循环的有向图。「根话题」即为全部话题的最上层的父话题。话题精华即为知乎的 Top1000 高票回答。请不要在问题上直接绑定「根话题」。这样会使问题话题过于宽泛。", "cids": [ "19778317", "19776751", "19778298", "19618774", "19778287", "19560891" ] }, { "id": "19778317", "value": "生活、艺术、文化与活动", "avatar": "https://pic4.zhimg.com/6df49c633_xs.jpg", "questions": "3.7M", "top-answers": "1000", "followers": "91K", "fid": "19776749", "desc": "以人类集体行为和人类社会文明为主体的话题,其内容主要包含生活、艺术、文化、活动四个方面。", "cids": [ "19551147", "19554825", "19550453", "19552706", "19551077", "19550434", "19552266", "19554791", "19553622", "19553632" ] },
Nightmare 做为爬虫的最大优点是只须要知道数据所在页面的 URL 就能够获取对应的同步/异步数据,并不须要详细的分析 HTTP 须要传递的参数。只须要知道进行哪些操做能使得网页页面数据更新,就能经过获取更新后的 HTML 片断得到对应的数据,在 Demo 中的 Nightmare 是打开了 chrome-dev 进行操做的,可是实际运行的时候是能够关闭的,关闭了以后其操做的速度会有必定的上升。下面的项目中还包含了另一个爬取的知乎的动态。
Demo源码地址: https://github.com/williamsta...
iKcamp原创新书《移动Web前端高效开发实战》已在亚马逊、京东、当当开售。