我在node.js
制作了一个网页抓取应用程序,它从网站的HTML中获取p.title
和p.artist
,然后将这两个元素中的每一个存储在两个单独的数组中,如下所示:
res.on('data', function(html){
var $ = cheerio.load(html);
var commonTitles = [];
var commonArtists = [];
commonTitles.push($.text($('p.title').eq(0)));
commonTitles.push($.text($('p.title').eq(1)));
commonTitles.push($.text($('p.title').eq(2)));
commonTitles.push($.text($('p.title').eq(3)));
commonTitles.push($.text($('p.title').eq(4)));
commonArtists.push($.text($('p.artist').eq(0)));
commonArtists.push($.text($('p.artist').eq(1)));
commonArtists.push($.text($('p.artist').eq(2)));
commonArtists.push($.text($('p.artist').eq(3)));
commonArtists.push($.text($('p.artist').eq(4)));
console.log(
'The 5 most recently played titles: \n' +
commonTitles[0] + ' / ' + commonArtists[0] + '\n' +
commonTitles[1] + ' / ' + commonArtists[1] + '\n' +
commonTitles[2] + ' / ' + commonArtists[2] + '\n' +
commonTitles[3] + ' / ' + commonArtists[3] + '\n' +
commonTitles[4] + ' / ' + commonArtists[4]
);
});
我想在网站上列出所有最近播放的5首歌曲,并在console.log
的帮助下将其打印出来。我希望在命令提示符下将其作为输出:
The 5 most recently played titles:
I Make It Rain (Original Trap Mix) / Jimithegenius
More Pragmatic (Original Version) / Jahnauasca
Kiss The Devil (Just A Gent Remix) / Bel Hair
Check (Levitate Remix) / Meek Mill
Party Right (Charlie Traplin Trap Mix) / Lethal Bizzle feat. Ruby Goe
播放列表偶尔会更新,所以这只是一个例子
而不是将它们打印出来,而是使用没有数组的其他参数打印出来,就像console.log
被放入这样一个奇怪的循环中一样:
The 5 most recently played titles:
/
/
/
/
/
The 5 most recently played titles:
/
/
/
/
/
The 5 most recently played titles:
I Make It Rain (Original Trap Mix) / Jimithegenius
More Pragmatic (Original Version) / Jahnauasca
Kiss The Devil (Just A Gent Remix) / Bel Hair
Check (Levitate Remix) / Meek Mill
Party Right (Charlie Traplin Trap Mix) / Lethal Bizzle feat. Ruby Goe
The 5 most recently played titles:
/
/
/
/
/
The 5 most recently played titles:
/
/
/
/
/
为什么打印出其他数据?
如果console.log
已经处于循环中,则所有附加输出都不会为空,所有这些输出都将包含来自数组的数据。我甚至尝试在res.on
之外创建数组作为全局数组,但随后它将标题和艺术家打印为undefined
。我如何摆脱这些不必要的线?
提前致谢,
的 Tim_W8
答案 0 :(得分:0)
您必须同时使用body
和data
进行操作才能完成这项工作。
end
。
data
。
end