我試圖從頁面上抓取圖像,但如果該頁面未完全加載,頁面將返回佔位符源attr(需要約0.5秒才能完全加載)我將如何提出請求等待?節點js請求和cheerio等待頁面完全加載
試着做
function findCommonMovies(movie, callback){
request('http://www.imdb.com/find?ref_=nv_sr_fn&q='+ movie +'&s=all', function (error, response, body) {
if (error){
return
}else{
var $ = cheerio.load(body);
var title = $(".result_text").first().text().split("(")[0].split(" ").join('')
var commonMovies = []
// var endurl = $("a[name=tt] .result_text a").attr("href")
var endurl = $('a[name=tt]').parent().parent().find(".findSection .findList .findResult .result_text a").attr("href");
request('http://www.imdb.com' + endurl, function (err, response, body) {
if (err){
console.log(err)
}else{
setInterval(function(){var $ = cheerio.load(body)}, 2000)
$(".rec_page .rec_item a img").each(function(){
var title = $(this).attr("title")
var image = $(this).attr("src")
commonMovies.push({title: title, image: image})
});
}
callback(commonMovies)
});
}
});
}
findCommonMovies("Gotham", function(common){
console.log(common)
})
不工作,我認爲它可能是異步.. –
你做了2秒的等待時間?你有更長的時間嗎?這是唯一的javascript函數(除了setInterval),它允許你暫停。你可以嘗試聲明一個函數:function cheerio(){var $ = cheerio.load(body)}然後setTimeout(cheero,2000);也許它不喜歡匿名函數 – Hunter
我很新的JavaScript,所以我可能是錯的,但不是在請求的響應('http://www.imdb.com'+ endurl,函數(錯誤,響應, body)已經被delcared了?我想也許有一種方法會等待 –