nodejs实现爬取网站图片功能
更新时间:2017年12月14日 14:16:47 投稿:laozhang
给大家通过一个实例来教学如何用nodejs实现爬取网站图片功能,有兴趣的朋友收藏一下吧。
通过实例给大家讲解nodejs实现爬取网站图片功能,以下就是全部内容:
原理:
爬虫是最明显的IO密集型应用场景,显然用node,使得I/O等待开销小数据挖掘比较方便
借助express模块来搭建node服务
并使用request模块获取目标页面的html代码
下载cheerio模块对html代码做处理(cheerio类似jQuery的语法,所以好用又方便)
环境配置:
npm install express request cheerio --save
(1)引入各个模块
var http = require('http'); var request = require('request); var cheerio = require('cheerio'); var fs = require('fs'); //用来操作文件 var url = 'https://movie.douban.com/cinema/nowplaying/beijing/' //定义要爬的页面
(2)发送请求
http.get(function(res){ var html = ''; var titles = []; res.setEncoding('utf-8') //防止中文乱码 res.on('data',function(chunk){ html += chrunk; //监听data事件 每次取一块数据 }) res.on('end',function(){ var $ = cheerio.load(html); //获取数据完成后,解析html //将获取的图片存到images文件夹中 $('.mod-bd img').each(function(index, item){ //获取图片属性 var imgName = $(this).parent().next().text().trimg() var imgfile = imgName + '.jpeg'; var imgSrc = $(this).attr('src') //采用request模块,向服务器发起请求 获取图片资源 request.head(imgSrc, function(error, res,body){ if(error){ console.log('失败了') } }); //通过管道的方式用fs模块将图片写到本地的images文件下 request(imgSrc).pipe.(fs.createWriteStream('./images/' + imgfile)); }) }) })
相关文章
浅谈node node-sass sass-loader版本对应问题
本文主要介绍了浅谈node node-sass sass-loader版本对应问题,文中通过示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下2021-09-09Node.js Continuation Passing Style( CPS与
这篇文章主要介绍了Node.js Continuation Passing Style,将回调函数作为参数传递,这种书写方式通常被称为Continuation Passing Style(CPS),它的本质仍然是一个高阶函数,CPS最初是各大语言中对排序算法的实现2022-06-06Node.js 中的 module.exports 与 exports区别介绍
这篇文章主要介绍了Node.js中的module.exports与exports区别介绍,每个模块中都有module对象,存放了当前模块相关的信息,更多相关内容需要的朋友可以参考一下2022-09-09
最新评论