网络编程 发布日期:2025/11/10 浏览次数:1
1.爬虫:爬虫,是一种按照一定的规则,自动地抓取网页信息的程序或者脚本;利用NodeJS实现一个简单的爬虫案例,爬取Boss直聘网站的web前端相关的招聘信息,以广州地区为例;
2.脚本所用到的nodejs模块
express 用来搭建一个服务,将结果渲染到页面
swig 模板引擎
cheerio 用来抓取页面的数据
requests 用来发送请求数据(具体可查:https://www.npmjs.com/package/requests)
async 用来处理异步操作,解决请求嵌套的问题,脚本中只使用了async.whilst(test,iteratee,callback),具体可见:https://caolan.github.io/async/
3.实现流程:
首先先获取到所爬取页面的URL,打开boss直聘网站,搜索web前端既可以获取到 https://www.zhipin.com/c101280100-p100901/"text-align: center">
然后通过Chrome浏览器打开F12,获取到信息中多对应的dom节点,即可知道想要获取信息;
4.代码实现
目录结构:
app.js
var cheerio = require('cheerio');
var requests = require('requests');
var async = require('async');
var express = require('express');
var swig = require('swig');
var app = express();
swig.setDefaults({cache:false});
app.set('views','./views/');
app.set('view engine','html');
app.engine('html',swig.renderFile);
app.get('/',function(req,res,next){
var page = 1; //当前页数
var list = []; //保存记录
async.whilst(
function(){
return page < 11;
},
function(callback){
requests(`https://www.zhipin.com/c101280100-p100901/"htmlcode">
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<style>
table{
width:1300px;
border:1px solid #ccc;
border-collapse: collapse;
text-align: center;
margin:0 auto;
}
td,tr,th{
border:1px solid #ccc;
border-collapse: collapse;
}
tr{
height:30px;
line-height: 30px;
}
</style>
<body>
<table>
<thead>
<tr>
<th>公司名称</th>
<th>公司地址</th>
<th>薪资</th>
<th>公司描述</th>
<th>岗位名称</th>
</tr>
</thead>
<tbody>
{% for list in lists %}
<tr>
<td>{{list.company}}</td>
<td>{{list.area}}</td>
<td>{{list.salary}}</td>
<td>{{list.description}}</td>
<td>{{list.job_title}}</td>
</tr>
{% endfor %}
</tbody>
</table>
</body>
</html>
5.启动
直接通过 node app.js启动即可;
6.运行结果(http://localhost:8080),只截取部分数据
总结
以上所述是小编给大家介绍的NodeJs实现简单的爬虫功能,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对网站的支持!