下載圖片


下載google的圖片


var request = require('request'),
    cheerio = require('cheerio'),
    fs = require('fs');

var imgDir = './images';
var keyword = process.argv[2];
var url = 'https://www.google.com.tw/search?q='+keyword+'&source=lnms&tbm=isch&sa=X&ved=0ahUKEwjy9v_wnYjUAhWCGJQKHW2gBEUQ_AUICigB&biw=1920&bih=396';

request(url, function(err, res, body) {
    if (!err && res.statusCode === 200) {
        var $ = cheerio.load(body);
        var imageUrls = [];
        $('img').each(function() {
            imageUrls.push($(this).attr('src'));
        });

        if (!fs.existsSync(imgDir)) {
            fs.mkdirSync(imgDir);
        }

        imageUrls.forEach(function(img, i) {
            request(imageUrls[i]).pipe(fs.createWriteStream(imgDir+'/google_' + i + '.jpg'));
        });
    }
});

下載dribbble的圖片



var request = require('request'),
    cheerio = require('cheerio'),
    fs = require('fs');

var url = 'https://dribbble.com'; //網址後加上?page=n,可以取得第12*(n-1)張開始的12張圖
var imgDir = './images';

request(url, function(err, res, body) {
    if (!err && res.statusCode === 200) {
        var $ = cheerio.load(body);
        var imageUrls = [];
        $('.dribbble .dribbble-img .dribbble-link picture source:first-child').each(function() {
            imageUrls.push($(this).attr("srcset"));
        });

        if (!fs.existsSync(imgDir)) {
            fs.mkdirSync(imgDir);
        }

        imageUrls.forEach(function(img, i) {
            request(imageUrls[i]).pipe(fs.createWriteStream(imgDir+'/dribble' + i + '.jpg'));
        });
    }
});

練習 - 試著用爬蟲抓取網路上的圖片

可以自己去找自己喜歡的網站,或是參考下列圖片網址

results matching ""

    No results matching ""