入门级节点爬虫github地址:https://github.com/lll618xxx/...是不是觉得社区文章太多了?哪个是我想要的?不怕比点赞数,不怕比标题,用node自己实现爬虫,麻麻再也不用担心我学习困难选择困难!核心代码constsuperagent=require('superagent')constcheerio=require('cheerio')constxlsx=require('node-xlsx')constfs=require('fs')constoptions=require('./options')superagent.get(options.url).then(res=>{constbufferdata=[{name:'sheet1',data:[options.attr.map((item,index,arr)=>{returnarr[index][2]})]}]const$=cheerio.load(res.text);$(options.ele).each((index,item)=>{letarr=[]options.attr.forEach((v,i,a)=>{arr.push(a[i][1]?$(item).find(a[i][0]).attr(a[i][1]):$(item).find(a[i][0]).text())})bufferdata[0].data.push(arr)})fs.writeFile(options.excelPath,xlsx.build(bufferdata),(错误)=>{如果(err)抛出错误;console.log('写入Excel成功');})}).catch(err=>{console.log(err)});核心代码只有36行!配置代码constpath=require('path')//定义爬虫页面consturl='https://segmentfault.com/hottest/monthly'//定义存放excel的路径constexcelPath=path.join(__dirname,'result.xlsx')//定义元素范围constele='div.wrapperdiv.news-listdiv.news__item-info'//定义数据属性['特定元素','属性','别名']constattr=[['a','href','链接'],['span.votes-num','','点赞数'],['h4.news__item-title','','titlename'],['span.authora','','作者姓名'],]安装依赖npmi运行项目cdnode-reptile-simple&&nodeindex.js配置项(options.js)url定义页面excelPath定义excel存放路径ele定义元素范围attr定义数据属性['特定元素','属性','别名']screenshot更完整的内容可以去github查看我做不到!
