NodeJS爬虫入门
爬虫是一种很实用的技术,比如说数据分析。今天我们来学习一个简单的Nodejs爬虫,理解其基本过程与基本原理。为了方便演示,我搭建了一个服务,建立了一个网页。如您对本文感兴趣,阅读完本文,可阅读下一篇:Nodejs爬虫入门(2)
我的服务地址:http://localhost:3000/
网页的数据内容如下:
可以看到这是一张展现2017年世界各国GDP的数据页面,右边是数据的HTML代码。接下来我们将获取这些数据。
首先安装request模块
request是一个简化的http操作模块,功能强大,简单方便。
通过get方式,获取页面
const request = require("request");
request('http://localhost:3000/', function (error, response, body) {
if(!error && response && response.statusCode === 200){
console.log(body.toString());
}
});
运行代码
可以看到,页面的HTML代码被抓取下来。但是抓取的HTML代码不方便我们进行数据的提取。
接下来安装cheerio模块,cheerio对jquery核心进行实现,API风格接近jquery。可以获取页面模板。
const request = require("request");
const cheerio = require("cheerio");
request('http://localhost:3000/', (error, response, body) => {
if(!error && response && response.statusCode === 200){
const $ = cheerio.load(body);
const th = $('thead th');
const data = [];
const arr = new Array(th.length).fill(0);
const title = $('h2').text();
const subtitle = arr.map((item, key)=> th.eq(key).text());
$('tbody tr').each((key, item) => {
const td = $(item).find('td');
data.push(arr.map((item, key)=> td.eq(key).text()));
})
console.log(title);
console.log(subtitle);
console.log(data);
}
});
运行代码
可以看到,已经获取到了页面的数据。接下来我们将存储数据。获取的数据可以存储在数据库,或者写入Excel。这里我们看看如何将数据写入Excel。我们借助node-xlsx来操作excel。首先我们在当前目录下新建一个gdp.xlsx文件
const request = require("request");
const cheerio = require("cheerio");
const xlsx = require('node-xlsx');
const fs = require('fs');
const path = require('path');
const time = Date.now();
request('http://localhost:3000/', (error, response, body) => {
if(!error && response && response.statusCode === 200){
const $ = cheerio.load(body);
const th = $('thead th');
const data = [];
const arr = new Array(th.length).fill(0);
const name = $('h2').text();
const subtitle = arr.map((item, key)=> th.eq(key).text());
$('tbody tr').each((key, item) => {
const td = $(item).find('td');
data.push(arr.map((item, key)=> td.eq(key).text()));
})
data.unshift(subtitle);
const buffer = xlsx.build([{name, data}]);
fs.writeFileSync(path.join(__dirname, 'gdp.xlsx'), buffer);
console.log(`执行完成,用时${Math.ceil((Date.now() - time)/1000)}秒`);
}
});
运行代码,查看结果
可以看到数据已经在Excel中。
总结:
通过这个例子,我们可以学习nodejs的基础知识,包括http基础知识、node相关的API,了解爬虫的基本过程与基本原理。面对复杂的应用场景,可能会遇到乱码,分页抓取数据,跨页面抓取数据,并发处理等情况。后续将会继续讨论这些场景。
666666666666
页:
[1]