当前位置: 首页 > 后端技术 > Node.js

!Ta居然用Node.js把这些美图做了这些事情,..

时间:2023-04-03 21:08:04 Node.js

做了什么?一个用来爬女神网女生图片的爬虫。如有侵权,一一下载太麻烦,立即关闭。如何使用0.node-v>=7.61。gitclonehttps://github.com/laihaibo/beauty-spider.git2。npmi3。npmrunstart(爬取相册图片链接并保存为json)4.npmruncalc(获取爬取的相册和文件数)5.npmrundownload(下载图片文件)updateagainst反爬虫图片下载完成后,你会发现它已经变成盗链图片了。然后观察浏览器的正常浏览行为。在请求头中设置referer、accept和user-agent。解决问题request.get(url).set({'Referer':'https://www.google.com','Accept':'image/webp,image/*,*/*;q=0.8','User-Agent':'Mozilla/5.0(WindowsNT10.0;Win64;x64)AppleWebKit/537.36(KHTML,likeGecko)Chrome/60.0.3091.0Safari/537.36'}).end((err,res)=>{})断线继续下载图片下载700个文件时,经常断线。应该是网站的爬虫机制起了作用,暂时解决不了。重新下载时应跳过已下载的文件。所以在保存图片的时候,会先判断图片是否存在。letisExit=fs.existsSync(path);if(!isExit){saveOne(...args)}获取应该下载的专辑和文件的数量letdata=JSON.parse(fs.readFileSync(path));让count=data.reduce((prev,cur)=>prev+cur.imgList.length,0);console.log(`共${data.length}张相册,共${count}张图片`);步骤引入所需的库constfs=require("fs");constmkdirp=require('mkdirp');constcheerio=require('cheerio');constrequest=require('superagent');要求('超级代理字符集')(请求);页面分析,配置config文件分析相册地址,以韩国为例,首页为https://www.nvshens.com/gallery/hanguo/,第二页为https://www.nvshens.com/gallery/hanguo/nvshens.com/gallery/hanguo/2.htmlconstconfig={current:'hanguo',allTags:{rougan:`https://www.nvshens.com/gallery/rougan/`,hanguo:'https://www.nvshens.com/gallery/hanguo/'}}封装了获取指定url的html内容的函数//网站编码为utf-8constgetHtml=url=>{returnnewPromise((resolve,reject)=>{request.get(url).charset('utf-8').end((err,res)=>{err?reject(err):resolve(cheerio.load(res.text));})})}获取所有专辑下的这个分类标签/***@param{string}startUrl标签首页的url地址*/constgetAlbums=(startUrl)=>{returnnewPromise((resolve,reject)=>{letalbums=[];//used保存标签所有相册信息(leti=1;i<=pages;i++){letpageUrl=`${startUrl+i}.html`//设置每个页面的urllet$=awaitgetHtml(pageUrl);//动态设置值页数letcompare=$('#listdiv.pagesYYa').map(function(i,el){returnparseInt($(this).text(),0);}).get().filter(x=>x>0);pages=conmpare.length<2?pages:compare.reduce((prev,cur)=>Math.max(prev,cur));$('.galleryli_titlea').each(函数(){albums.push({title:$(this).text(),url:`https://www.nvshens.com${$(this).attr("href")}`,imgList:[],id:parseInt($(this).attr("href").split('/')[2],10)})})}resolve(albums);//返回专辑信息}catch(error){console.log(error);}}getQuery(startUrl);})}获取所有相册的图片信息/***@param{string}startUrl相册首页的url地址*/constgetImgList=(startUrl)=>{returnnewPromise((resolve,reject)=>{letalbums=[];//存储本专辑所有图片信息letgetQuery=asyncstartUrl=>{try{let$=awaitgetHtml(startUrl);letpages=$('#pagesa').length;for(leti=1;i<=pages;i++){letpageUrl=`${startUrl+i}.html`let$=awaitgetHtml(pageUrl);$('#hgalleryimg').each(function(){leturl=$(this).attr('src');//图片地址letfileName=url.split('/').pop();//文件名letid=parseInt(fileName.split('.')[0],10);//idalbums.push({url,文件名,id})})}resolve(专辑);//返回本专辑所有图片信息}catch(error){console.log(error);}}getQuery(startUrl);})}保存专辑信息/***@param{string}path保存数据的路径*@param{array}专辑专辑信息数组*/constsaveData=(path,albums)=>{fs.writeFile(path,JSON.stringify(albums,null,''),function(err){err?console.log(err):console.log('Datasaved');});}保存图片/**12.@param{string}title图片所在文件夹名称13.@param{string}url图片url14.@param{string}fileName图片名称15.@param{array}imgList单个相册的图片信息*///保存图像constsaveOne=(title,url,fileName)=>{returnnewPromise((resolve,reject)=>{letpath=`./img/${currentImgType}/${title}/${fileName}`;request.get(url).end((err,res)=>{if(err){console.log(`Error:${err}ingetting${url}`)}fs.writeFile(path,res.body,function(err){if(err)console.log(`Error:${err}indownloading${url}`)});解决();})})}//在相册中保存多张图片constsaveImg=({title,imgList})=>{//创建文件夹mkdirp(`./img/${currentImgType}/${title}`,function(err){if(err){console.log(`Error:${err}inmadedir${title}`);}});letgetQuery=async()=>{try{for(let{url,fileName}ofimgList){awaitsaveOne(title,url,fileName);}}catch(错误){console.log(错误);}}//打印下载专辑所需的时间console.time(`download${title}...`)getQuery();console.timeEnd(`download${title}...`)}执行爬虫constdoSpider=async()=>{try{//获取专辑信息letalbums=awaitgetAlbums(allTags[current]);//获取每张图片的信息for(letalbumofalbums){letimgList=awaitgetImgList(album.url);album.imgList=imgList;}//保存jsonletjsonPath=`./data`;mkdirp(jsonPath,function(err){if(err){console.log(`Error:${err}inJson的madedir`);}});保存数据(`${jsonPath}/${currentImgType}.json`,专辑);//保存图像(letvalueofalbums){saveImg(value)}}catch(error){console.log(error);}}经验体会有些坑不踩再踩就不会吐血,比如cheerio的操作,fs的操作justdoit。感谢这篇文章参考了nieheyong的HanhandeSpider等爬虫文章,得到了很多启发