手把手教你用Node.js爬虫爬取网站数据的方法
开始之前请先确保自己安装了Node.js环境,还没有安装的的童鞋请看一下安装教程......
https://www.nhooo.com/article/113677.htm
https://www.nhooo.com/article/57687.htm
直接开始吧
1.在项目文件夹安装两个必须的依赖包
npminstallsuperagent--save-dev
SuperAgent(官网是这样解释的)
-----SuperAgentislight-weightprogressiveajaxAPIcraftedforflexibility,readability,andalowlearningcurveafterbeingfrustratedwithmanyoftheexistingrequestAPIs.ItalsoworkswithNode.js!
-----superagent是一个轻量的,渐进式的ajaxapi,可读性好,学习曲线低,内部依赖nodejs原生的请求api,适用于nodejs环境下
npminstallcheerio--save-dev
Cheerio
-----cheerio是nodejs的抓取页面模块,为服务器特别定制的,快速、灵活、实施的jQuery核心实现。适合各种Web爬虫程序。相当于node.js中的jQuery
2.新建 crawler.js 文件
//导入依赖包
consthttp=require("http");
constpath=require("path");
consturl=require("url");
constfs=require("fs");
constsuperagent=require("superagent");
constcheerio=require("cheerio");
3.看注释啦(这里爬取的是boss直聘网站的数据)
superagent
.get("https://www.zhipin.com/job_detail/?city=100010000&source=10&query=%E5%89%8D%E7%AB%AF")
.end((error,response)=>{
//获取页面文档数据
varcontent=response.text;
//cheerio也就是nodejs下的jQuery将整个文档包装成一个集合,定义一个变量$接收
var$=cheerio.load(content);
//定义一个空数组,用来接收数据
varresult=[];
//分析文档结构先获取每个li再遍历里面的内容(此时每个li里面就存放着我们想要获取的数据)
$(".job-listli.job-primary").each((index,value)=>{
//地址和类型为一行显示,需要用到字符串截取
//地址
letaddress=$(value).find(".info-primary").children().eq(1).html();
//类型
lettype=$(value).find(".info-companyp").html();
//解码
address=unescape(address.replace(//g,'%u').replace(/;/g,''));
type=unescape(type.replace(//g,'%u').replace(/;/g,''))
//字符串截取
letaddressArr=address.split('');
lettypeArr=type.split('');
//将获取的数据以对象的形式添加到数组中
result.push({
title:$(value).find(".name.job-title").text(),
money:$(value).find(".name.red").text(),
address:addressArr,
company:$(value).find(".info-companya").text(),
type:typeArr,
position:$(value).find(".info-publis.name").text(),
txImg:$(value).find(".info-publisimg").attr("src"),
time:$(value).find(".info-publisp").text()
});
//console.log(typeof$(value).find(".info-primary").children().eq(1).html());
});
//将数组转换成字符串
result=JSON.stringify(result);
//将数组输出到json文件里刷新目录即可看到当前文件夹多出一个boss.json文件(打开boss.json文件,ctrl+A全选之后ctrl+K,再Ctrl+F即可将json文件自动排版)
fs.writeFile("boss.json",result,"utf-8",(error)=>{
//监听错误,如正常输出,则打印null
if(error==null){
console.log("恭喜您,数据爬取成功!请打开json文件,先Ctrl+A,再Ctrl+K,最后Ctrl+F格式化后查看json文件(仅限VisualStudioCode编辑器)");
}
});
});
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。