【发布时间】:2014-11-09 20:39:30
【问题描述】:
我正在尝试为我从 officialcharts.com 抓取的数据获取 youtube 视频。 我能够抓取数据并为他们获取 youtube 网址。但是当我尝试推动 仅将标题和艺术家姓名推送到数组中。变量 youtubeUrl 没有被赋值。为什么变量 youtubeUrl 不在范围内?
我尝试了多种方法。我尝试在搜索功能内声明 youtubeUrl,然后在请求外声明,但我遇到了同样的问题。
我也尝试将 json.tracks.push 移动到搜索功能中,但 json 不在范围内,因此没有任何内容添加到轨道
我正在使用https://www.npmjs.org/package/youtube-search 搜索视频。
// Scraping charts
app.get('/scrape', function(req, res){
url = 'http://www.officialcharts.com/music-charts/';
request(url, function(error, response, html){
if(!error){
var $ = cheerio.load(html);
var title, artist, youtubeUrl;
var json = {tracks:[]};
$('div .infoHolder').each(function(){
var data = $(this);
var opts = {
maxResults: 1,
startIndex: 1
};
// Scrapped title and artist name
title = data.children('h3').text();
artist = data.children('h4').text();
// Searching for youtube videos
search(title, opts, function (err, results) {
if (err) {
return console.log(err);
}
youtubeUrl = results[0].url;
})
console.log(youtubeUrl); // THIS IS RETURNED UNDEFINED
// youtubeUrl IS NOT PUSHED TO THE ARRAY
// ONLY TITLE AND ARTIST PUSHED
json.tracks.push({title:title,artist:artist,url: youtubeUrl});
})
}
res.send(json);
})
})
【问题讨论】:
-
search是一个 异步 方法,因此只有在搜索成功时才会执行回调函数(search的第三个参数)。当你把你的console.log放在search之后而不是在回调中时,你什么都没有...... -
搜索是你写的自定义方法吗? .把它的来源也写出来。
标签: javascript json node.js youtube cheerio