Node+Async库实现爬虫异步的串行执行

205 阅读1分钟

使用node爬取页面内容的时候因为方法都是异步执行使得请求的地址会一时间得到大量请求而出现问题,从而导致请求失败或者ip被封等情况,所以要控制请求量防止一时间请求量大而引发的错误,这里使用的第三方库Async处理异步并发、cheerio获取元素节点、axios请求资源。

1.第一步安装cheerio、axios、async库

npm install cheerio
npm install axios
npm install async

2.引入async等模块库

引入模块
const async = require('async');
const axios = require("axios");

3.定义一个数组,将数据添加到数组中

let urls = []

声明一个方法传入要爬取的网络地址,使用axios请求网页数据、cheerio获取返回的html结构的内容并分析

async function getList(url){
	let {data:res} = await axios.get(url)
	const $ = cheerio.load(res)
	let brief = $('#intro > p:nth-child(1)')//这个地方填结构
		 $('#list > dl > dd > a').each((i,item)=>{
			urls.push(url + item.attribs.href)
		 })
		 async.mapLimit(urls,1,function(url,callback){
		 	getData(url,callback)
		 },function(err,result){
		 	console.log('final:',result);
		 }
		 )
}

声明一个获取文章内容的方法

async function getData(url,callback){ //获取文章内容
	let {data:res} = await axios.get(url)
	const $ = cheerio.load(res)
	let content = $('#content').html()
	callback(null,content)
}