我正在尝试从页面上抓取图像,但是如果该页面未完全加载,页面会返回一个占位符源attr(完全加载大约需要0.5秒),我将如何使请求等待?

尝试做

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

最佳答案

Cheerio不是Web浏览器。 它只是HTML的解析器。这意味着发出异步请求的javascript函数没有被执行。

所以。除非您使用充当网络浏览器的功能,否则您将无法做您想做的事情。例如,Selenium将API添加到许多Web浏览器中。

您需要下载Selenium客户端并保持运行,只要您想继续向具有异步内容加载功能的网站发出请求。

另外,您将需要根据您使用的语言和所需的Webdriver进行包装。 Webdriver用于添加对不同Web浏览器的支持。

我假设您正在使用NodeJS或基于js的类似内容,所以here you go.

并确保检查API.

希望对您有所帮助。

您还可以检查PhantomJS.

关于javascript - Node js请求和cheerio等待页面完全加载,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46595877/

10-10 00:51
查看更多