使用Node.js从网站获取图像

时间:2016-12-09 17:27:15

标签: node.js

我正在制作自己的Discord机器人,而且我以前没有使用过JS的经验。我正在制作一个能够从此网站下载和发布图片的功能:http://random.dog

当我知道图片的确切链接时,我已成功从其他地方下载图像。这是我的代码的相关部分:

var download = function(uri, filename, callback){

request(uri).pipe(fs.createWriteStream(filename)).on('close', callback);}

download('http://random.dog/14769-27888-18622.jpg', 'dog.png',

我正在使用此请求模块https://www.npmjs.com/package/reques,是否可以使用该模块获取没有确切网址的图片?

1 个答案:

答案 0 :(得分:0)

  

您可以动态获取网址并下载带有名称的图片,您需要这两个模块request-promise, cheerio,

var app = require('express')();

    var http = require('http').Server(app);

fs = require('fs');   

var fs = require('fs'),
    request = require('request');
//save image 

    var download = function(uri, filename, callback){
      request.head(uri, function(err, res, body){
    request(uri).pipe(fs.createWriteStream(filename)).on('close', callback);
  });
};

//get URL
var Imgpath="";
var rp = require('request-promise'),
    cheerio = require('cheerio'),
    url = require('url'),
    base = 'http://random.dog/';

var options = {
    uri: base,
    method: 'GET',
    resolveWithFullResponse: true
};
rp(options)
  .then (function (response) {
    $ = cheerio.load(response.body);
    var relativeLinks = $("img");
    relativeLinks.each( function() {
        var link = $(this).attr('src');
        var fullImagePath = url.resolve(base, link); // should be absolute 
   //pass to download to download image link is file name and base is base url
        download(base+link,link,function()
                {
            console.log("wao great we done this...THINK DIFFERENT")
        })
   });
});
app.listen(3000);
console.log("server start");
app.get('/',function(req,res){
    res.sendfile(__dirname + '/a.html');
});

enter image description here