【发布时间】:2016-10-10 13:45:50
【问题描述】:
所以我想使用 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');
}
});
});
结果
/logos/doodles/2016/phoebe-snetsingers-85th-birthday-5179281716019200-hp.gif
rel
【问题讨论】:
-
@Midas 这个问题与其他问题密切相关,但由于在这种情况下 DOM 和 jQuery 以及在这种情况下 Cheerio 之间的实现差异,这个问题并不完全重复。执行 $(this) 或 $('img')[0].src 之类的操作不会在 Cheerio 中返回任何内容。
标签: javascript html node.js cheerio