手把手教你用Node.js爬虫爬取网站数据的方法

2020-06-17 06:03:51易采站长站整理

开始之前请先确保自己安装了Node.js环境,还没有安装的的童鞋请看一下安装教程……

https://www.jb51.net/article/113677.htm

https://www.jb51.net/article/57687.htm

直接开始吧

1.在项目文件夹安装两个必须的依赖包


npm install superagent --save-dev

SuperAgent(官网是这样解释的)

—–SuperAgent is light-weight progressive ajax API crafted for flexibility, readability, and a low learning curve after being frustrated with many of the existing request APIs. It also works with Node.js!

—–superagent 是一个轻量的,渐进式的ajax api,可读性好,学习曲线低,内部依赖nodejs原生的请求api,适用于nodejs环境下


npm install cheerio --save-dev

Cheerio

—–cheerio是nodejs的抓取页面模块,为服务器特别定制的,快速、灵活、实施的jQuery核心实现。适合各种Web爬虫程序。相当于node.js中的jQuery

2.新建  crawler.js  文件


//导入依赖包
const http = require("http");
const path = require("path");
const url = require("url");
const fs = require("fs");

const superagent = require("superagent");
const cheerio = 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)=>{
//获取页面文档数据
var content = response.text;
//cheerio也就是nodejs下的jQuery 将整个文档包装成一个集合,定义一个变量$接收
var $ = cheerio.load(content);
//定义一个空数组,用来接收数据
var result=[];
//分析文档结构 先获取每个li 再遍历里面的内容(此时每个li里面就存放着我们想要获取的数据)
$(".job-list li .job-primary").each((index,value)=>{
//地址和类型为一行显示,需要用到字符串截取
//地址
let address=$(value).find(".info-primary").children().eq(1).html();
//类型
let type=$(value).find(".info-company p").html();
//解码
address=unescape(address.replace(/&#x/g,'%u').replace(/;/g,''));
type=unescape(type.replace(/&#x/g,'%u').replace(/;/g,''))
//字符串截取
let addressArr=address.split('<em class="vline"></em>');
let typeArr=type.split('<em class="vline"></em>');
//将获取的数据以对象的形式添加到数组中
result.push({
title:$(value).find(".name .job-title").text(),
money:$(value).find(".name .red").text(),