随手写个node爬虫
2017-10-27 16:34
239 查看
以下案例是用node爬取百度传课,获取免费视频课程信息,并下载展示图片
const fs = require('fs'); const fetch = require('node-fetch'); const cheerio = require('cheerio'); const URL = require('url'); const url = 'https://chuanke.baidu.com/course/72351176577777664__cost_asc___2.html'; const protocol = URL.parse(url).protocol; const host = URL.parse(url).host; const fsName = 'java_course.txt'; const imgPath = './images/'; let page = 1; startSpider(); function startSpider() { console.log('爬虫开始...'); fs.writeFileSync(fsName, '百度传课' + '\n'); itemSpider(url); } function itemSpider(url) { // 单页爬虫 (async function () { try { console.log('当前页面', url); let html = await fetch(url).then(res => res.text()); fs.appendFileSync(fsName, '这是第' + page + '页'); page += 1; let $ = cheerio.load(html); queryData($); // 处理数据 if (page < 50) { setTimeout(() => { spiderNext($); // 继续下一页 }, 1000); } } catch (exception) { console.log('出错了:', exception); } })(); } function queryData($) { try { let panels = $('.item-panel' 4000 ); panels.map((index, item) => { let tittle = $(item).find('.item-title a').text(); let href = protocol + $(item).find('.item-title a').attr('href'); let price = $(item).find('.price span').text(); let text = tittle + ' (' + price + ') ' + href + '\n'; let src = protocol + $(item).find('img').attr('src'); downImg(tittle, src); fs.appendFile(fsName, text, (err) => { if (!err) { console.log(tittle); } }); }); } catch (exception) { console.log(exception); } } function spiderNext($) { let nextUrl = protocol + '//' + host + $('.ck-page .next').attr('href'); itemSpider(nextUrl); } function downImg(tittle, src) { try { fetch(src).then(res => { res.body.pipe(fs.createWriteStream(imgPath + tittle + '.jpg')); }); } catch (exception) { console.log(exception); } }
相关文章推荐
- Node.js爬虫数据抓取乱码问题总结
- 用node.js写的http小爬虫
- 利用node.js写一个爬取知乎妹纸图的小爬虫
- node爬虫
- Node.js+jade+mongodb+mongoose实现爬虫分离入库与生成静态文件的方法
- Node.js爬虫--网页请求模块
- 基于superagent 与 cheerio 的node简单爬虫
- Node.js(十三)——Promise重构爬虫代码
- 详解Node.js API系列 Http模块(2) CNodejs爬虫实现
- Node.js爬虫抓取数据 -- HTML 实体编码处理办法
- Node.js 爬虫批量下载美剧 from 人人影视 HR-HDTV
- [置顶] 简单的node爬虫练手,循环中的异步转同步
- Node.js编写爬虫的基本思路及抓取百度图片的实例分享
- Node.js之网络小爬虫
- node 爬虫 --- 将爬取到的数据,保存到 mysql 数据库中
- 从零学习node.js之简易的网络爬虫(四)
- node.js 小爬虫抓取网页数据
- 基于node.js的一个小爬虫
- Node.js简单爬虫开发过程