如何用Node写页面爬虫的工具集

2020-06-17 05:57:58易采站长站整理

最近做了几个写爬虫的小项目(从页面端到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的代码,欢迎查看:

https://github.com/SP-Lyu/puppeteer_weibo_cookie/blob/master/index.js

由于 Puppeteer 基于Chromium,每次都需要载入页面再进行页面分析,性能十分有限,下面提到的 cheerio 则可以从另一层面解决这个问题。

文档

GitHub 

中文API地址

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

Auto.js

国人开发的,使用js编写代码操作Android设备的自动化工具,对于爬取某些加固措施较好的APP来说十分有用,而且有非常完善的文档以及社区,十分良心。