【问题标题】:How do I scrape a site with phantomjs?如何使用 phantomjs 抓取网站?
【发布时间】:2013-02-27 07:06:19
【问题描述】:

我正在尝试抓取网站并获取 iTunes 促销代码。经过一番实验,我发现我可以很容易地使用 JavaScript 控制台获取代码:http://cl.ly/image/3U1K2a2b1f36/console.png

此后不久,我用 PhantomJS 尝试了以下操作:

 var page = require('webpage').create();
 page.open('http://www.air1.com/music/free-songs.aspx', function () {
     code = page.evaluate(function() {
         __doPostBack('ctl00$cphRight1$itunesPromo$lbGetDownloadCode','');
         return document.getElementById('ctl00_cphRight1_itunesPromo_lblItunesCodes').innerText;
     });

     console.log('Code: ' + code);
     phantom.exit();
 });

它没有像我想象的那样工作——code 返回为空。

【问题讨论】:

    标签: javascript phantomjs


    【解决方案1】:

    在调用加载它和调用获取 innerText 之间,弹出窗口可能不在 DOM 中。尝试在两者之间暂停。

    var page = require('webpage').create();
    page.open('http://www.air1.com/music/free-songs.aspx', function (status) {
    
      if (status !== 'success') {
        console.log('error');
        phantom.exit();
        return;
      }
    
      page.evaluate(function() {
        __doPostBack('ctl00$cphRight1$itunesPromo$lbGetDownloadCode','');
      });
    
      setTimeout(function() {
       var code = page.evaluate(function() {
         return document.getElementById('ctl00_cphRight1_itunesPromo_lblItunesCodes').innerText;
       });
       console.log('code = ' + code);
       phantom.exit();
      }, 1000);
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多