
搭建环境:
1、创建一个文件夹,进入并初始化一个package.json文件。
npm init -y
2、安装相关依赖:
npm install --save koa npm install --save cheerio // 后面会用到,用于抓取页面模块,为服务器特别定制的,快速、灵活、实施的jQuery核心实现
爬取网站数据的代码如下(文件名:demo2.js):
var http = require('http') // Node.js提供了http模块,用于搭建HTTP服务端和客户端
var url = 'http://www.m4yy.com/type/2.html' //输入任何网址都可以
http.get(url,function(res){ //发送get请求
var html=''
res.on('data',function(data){
html += data //字符串的拼接
})
res.on('end',function(){
console.log(html)
})
}).on('error',function(){
console.log('获取资源出错!')
})实现效果:

在刚刚的js文件中引入cheerio模块,然后加载所需要的html内容。
var $ = cheerio.load(html) // 加载需要的html
为了方便使用,这里封装一个函数:
var http = require('http') // Node.js提供了http模块,用于搭建HTTP服务端和客户端
var url = 'http://www.m4yy.com/type/2-3.html' //输入任何网址都可以
var cheerio = require('cheerio') // 抓取页面模块,为服务器特别定制的,快速、灵活、实施的jQuery核心实现
http.get(url,function(res){ //发送get请求
var html=''
res.on('data',function(data){
html += data //字符串的拼接
})
res.on('end',function(){
var courseData = filterChapters(html)
console.log('courseData', courseData)
})
}).on('error',function(){
console.log('获取资源出错!')
})
function filterChapters(html) {
var $ = cheerio.load(html) // 加载需要的html
var chapters = $('.movie-item') //在html里寻找需要的资源的class
var courseData = [] // 创建一个数组,用来保存资源
chapters.each(function(item, index) { //遍历html文档
var chapter = $(this)
var chapterTitle = chapter.children('a').attr('title')
var tvUrl = chapter.children('a').attr('href').split('show/')[1]
var imgUrl = chapter.find('img').attr('src')
var updateStatus = chapter.find('.hdtag').text()
var type = chapter.find('.otherinfo a').text()
var url = `http://www.m4yy.com/show/${tvUrl}`
courseData.push({
chapterTitle: chapterTitle,
tvUrl: tvUrl,
imgUrl: imgUrl,
updateStatus: updateStatus,
type: type,
url: url
})
})
return courseData //返回需要的资源
}再次执行node demo2.js 此时结果如下:

以上就是使用node怎么爬取一个网站的数据?的详细内容,更多请关注易知道|edz.cc其它相关文章!














