注:本文只討論技術(shù)不涉及商業(yè),如有侵權(quán)請(qǐng)告知,未經(jīng)本人同意轉(zhuǎn)載后果自負(fù)!
本文是通過(guò)瀏覽器端ajax,node端request-json進(jìn)行爬取”尤果網(wǎng)“部分圖片資源,純屬技術(shù)方面興趣,不涉及商業(yè)方面;
先上圖:

如果沒(méi)有node基礎(chǔ)請(qǐng)自行學(xué)習(xí)~
獲取圖片原理:通過(guò)request請(qǐng)求html文件,利用正則匹配圖片路徑獲取到當(dāng)前頁(yè)面圖片的數(shù)組,發(fā)送到瀏覽器端,進(jìn)行展示;
1.安裝request-json (cnpm i request-json --save)
2.安裝express(cnpm i express --save)
3.新建一個(gè)app.js文件,作為server文件,代碼如下
const express = require("express");const morgan = require('morgan');const ejs = require('ejs');const path = require('path');const bodyParser = require('body-parser');const app = express();//logs info to serverapp.use(morgan('dev'));//post resolveapp.use(bodyParser.json());app.use(bodyParser.urlencoded({extended: false}));// view engine setupapp.engine('html', ejs.__express);app.set('views', path.join(__dirname, 'views'));app.set('view engine', 'html');//設(shè)置靜態(tài)文件如:圖片, CSS, JavaScript 等。app.use(bodyParser.json());app.use(bodyParser.urlencoded({extended: false}));app.use(express.static(path.join(__dirname, 'public')));/** reuire pages*/var index = require('./routes/index')/** render pages*/app.use('/', index);// catch 404 and forward to error handlerapp.use(function(req, res, next) {var err = new Error('Not Found');err.status = 404;next(err);});// error handlerapp.use(function(err, req, res, next) {// set locals, only providing error in developmentres.locals.message = err.message;res.locals.error = req.app.get('env') === 'development' ? err : {};// render the error pageres.status(err.status || 500);res.render('error', {"title": '404',"msg": '服務(wù)異常'});});module.exports = app;app.listen(3000,function(){console.log('http://127.0.0.1:3000')});此時(shí)服務(wù)運(yùn)行在3000端口;
4.請(qǐng)求html頁(yè)面:
router.all("/getUGirls",function(req,res,next){
正則部分代碼(……)
client.get(url,function(err, response, body) { if((typeof body)!="string"){ body = JSON.stringify(body); } arr =body.match(reg); console.log(arr); //這里就是當(dāng)前頁(yè)面的路徑以及頁(yè)面上圖片列表的數(shù)組,通過(guò)res.json發(fā)送到client; res.json({"url":url,"records":arr});});})該方法適用于頁(yè)面url有規(guī)則,并且頁(yè)面中圖片路徑有規(guī)則的任何網(wǎng)站的圖片爬取;
再次聲明,不要隨便那人家網(wǎng)站上的圖片隨便使用,學(xué)學(xué)技術(shù)就好,況且這個(gè)方法沒(méi)什么技術(shù)含量,源碼就不放了;
不說(shuō)了,看圖去了
以上這篇ajax+node+request爬取網(wǎng)絡(luò)圖片的實(shí)例(宅男福利)就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持武林網(wǎng)。
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注