小编bse*_*ego的帖子

如何从response.body中获取节点中'<img rel="nofollow noreferrer" src =''>'的绝对路径

所以我想使用request-promise来拉取页面的主体.一旦我有了页面,我想收集所有标签并获得这些图像的src数组.假设页面上的src属性具有相对路径和绝对路径.我想要一个页面上的imgs绝对路径数组.我知道我可以使用一些字符串操作和npm路径来构建绝对路径,但我想找到一种更好的方法.

var rp = require('request-promise'),
    cheerio = require('cheerio');

var options = {
    uri: 'http://www.google.com',
    method: 'GET',
    resolveWithFullResponse: true
};

rp(options)
  .then (function (response) {
    $ = cheerio.load(response.body);
    var relativeLinks = $("img");
    relativeLinks.each( function() {
        var link = $(this).attr('src');
        console.log(link);
        if (link.startsWith('http')){
            console.log('abs');
        }
        else {
            console.log('rel');
        }
   });
});
Run Code Online (Sandbox Code Playgroud)

结果

  /logos/doodles/2016/phoebe-snetsingers-85th-birthday-5179281716019200-hp.gif
  rel
Run Code Online (Sandbox Code Playgroud)

html javascript node.js cheerio

5
推荐指数
1
解决办法
2841
查看次数

标签 统计

cheerio ×1

html ×1

javascript ×1

node.js ×1