最近做了几个写爬虫的小项目 (从页面端到 App 端的都有), 在网上搜寻了一番好用的爬虫工具, 做了个工具集整理:
Puppeteer
简介
Puppeteer 是一个 Node 库, 它提供了一个高级 API 来通过 DevTools 协议控制 Chromium 或 Chrome. 简单点说, 就是使用 Node 命令控制一个无需渲染至用户界面的浏览器.
与使用 PhantomJS 搭配 Python 进行爬虫抓取类似, 其原理也是去完全地模拟一个浏览器进行页面的渲染, 从而抓取其中某些特定的内容.
特性
Puppeteer 可以完整地模拟一个浏览器的行为, 并且可以进行截图, 拦截浏览器请求, 获取 Cookie, 通过 Node 注入 JS 代码等操作, 使用 Chrome 浏览器开发者工具能做到的, Puppeteer 也能做到.
使用起来也十分的简单, 以下是官方的例子:
- const puppeteer = require('puppeteer');
- (async () => {
- const browser = await puppeteer.launch();
- const page = await browser.newPage();
- await page.goto('https://example.com');
- await page.screenshot({path: 'example.png'});
- await browser.close();
- })();
在 GitHub 上放了一份自己写的使用 Puppeteer 获取微博 cookie 的代码, 欢迎查看:
由于 Puppeteer 基于 Chromium, 每次都需要载入页面再进行页面分析, 性能十分有限, 下面提到的 cheerio 则可以从另一层面解决这个问题.
文档
GitHub https://github.com/GoogleChrome/puppeteer
中文 API 地址 https://zhaoqize.github.io/puppeteer-api-zh_CN/#/
cheerio
cheerio 是一个轻型灵活, 类 jQuery 的对 html 元素分析操作的工具. 在进行一些 server 端渲染的页面以及一些简单的小页面的爬取时, cheerio 十分好用且高效.
特性
cheerio 包括了 jQuery 的核心子集, 意味着可以直接使用 jQuery 的 API 进行元素的操控, 官方的例子:
- const cheerio = require('cheerio')
- const $ = cheerio.load('<h2 class="title">Hello world</h2>')
- $('h2.title').text('Hello there!')
- $('h2').addClass('welcome')
- $.HTML()
- //=> <h2 class="title welcome">Hello there!</h2>
自己写的获取某个网站的所有 a 链接:
- const cheerio = require('cheerio');
- const get = function(){/*HTTP get 请求...*/}
- (async ()=>{
- const HTML = await get(`http://example.com`);
- const $ = cheerio.load(HTML);
- const $dom_arr = $('a');
- $dom_arr.each((index, elem)=>{
- const url = $(elem).attr('href') || '';
- console.log(url);
- });
- })();
文档
GitHub https://github.com/cheeriojs/cheerio
Auto.JS
国人开发的, 使用 JS 编写代码操作 Android 设备的自动化工具, 对于爬取某些加固措施较好的 App 来说十分有用, 而且有非常完善的文档以及社区, 十分良心.
使用 Auto.JS 进行设备自动化操作, 再通过代理进行请求数据的获取, 能绕开加固中难以破解的加密串.
特性
作为爬虫工具, 好处有:
采用 JavaScript 作为脚本语言开发, JS 开发者 0 成本接入;
兼容性良好, 大多数任务不需要 root 权限;
自带界面分析工具, 方便定位需要操作的元素.
从 Auto.JS 载入某个 App, 并点击进入某个频道的例子:
- // 声明环境
- auto();
- // 设备常亮
- device.keepScreenDim();
- // 调起 App
- launchApp('头条');
- sleep(10000);
- // 找到某个频道, 并点击进入
- var rect = text('视频').findOnce().bounds();
- var x = rect.centerX();
- var y = rect.centerY();
- click(x, y);
- // 点击进入详情, 使用代理抓取并处理请求...
- ...
文档
GitHub https://github.com/hyb1996/Auto.js
中文文档 https://hyb1996.github.io/AutoJs-Docs/#/
来源: https://www.jb51.net/article/149589.htm