2014-02-07 50 views
1

我對過多的刮擦技術有點新,所以我一直在測試一堆。我正在看的一個測試頁面是here。我注意到,通過Capybara的刮板正在返回我期望的結果 - JS運行後的HTML。這裏是代碼:爲什麼webkit通過capybara獲得與CasperJS不同的結果?

class Scraper 
    include Capybara::DSL 

    Capybara.run_server = false 
    Capybara.current_driver = :webkit 

    def test_scrape  
     visit "https://www.facebook.com/pages/Buddha-Bodai-Vegetarian-Restaurant/117609928256672?sk=info" 
     if body.match /pagelet_nearby_places_results/ 
     has_xpath?("//div[@id='pagelet_nearby_places_results']") 
     end 
     body 
    end 
    end 

這顯然是一個非常基本的測試。例如,您可以通過查看頁面上Foursquare鏈接的HTML來正確加載。

<a class="uiIconText" href="https://www.facebook.com/l.php?u=https%3A%2F%2Ffoursquare.com%2Fv%2Fbuddha-bodai%2F459b830af964a5208b401fe3%3Fref%3Datw&amp;h=0AQH4z1yv&amp;s=1" 
... 

我還測試實施CasperJS解決方案,如下圖所示:

var casper = require('casper').create({ 
    pageSettings: { 
    javascriptEnabled: true, 
    loadImages: false, 
    loadPlugins: false, 
    userAgent: 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/536.5 (KHTML, like Gecko) Chrome/19.0.1084.9 Safari/536.5' 
    } 
}); 


result = {}; 

casper.start("https://www.facebook.com/pages/Buddha-Bodai-Vegetarian-Restaurant/117609928256672?sk=info", function() { 
    var body = this.getHTML(); 
    if(body.indexOf('pagelet_nearby_places_results') >= 0){ 
     casper.waitForSelector('div#pagelet_nearby_places_results', function() { 
      result.html = this.getHTML(); 
     }); 
    }else{ 
     result.html = body; 
    }  
}); 

casper.run(function complete() { 
    this.echo(JSON.stringify(result, null, 4)); 
    this.exit(); 
}); 

爲此,我得到這似乎是HTML的JS加載之前不同的結果。在這種情況下,Foursquare的鏈接被註釋掉和代碼標籤內:

<code class="hidden_elem" id="u_0_i"><!-- <div class="_5ay5"><div data-gt="{&quot;vertex_section&quot;:&quot;VertexLinksSection&quot;}"><div class="_gl"><div class="_117 _4qd"><h3>Links</h3></div><div class="_gm"><ul class="uiList _4kg _6-h _6-j _6-i"><li class="_6zy"><table class="uiGrid _51mz" cellspacing="0" cellpadding="0"><tbody><tr class="_51mx"><td class="_51m-"><a class="uiIconText" href="https://www.facebook.com/l.php?u=https%3A%2F%2Ffoursquare.com%2Fv%2Fbuddha-bodai%2F459b830af964a5208b401fe3%3Fref%3Datw&amp;h=UAQG_81FD&amp;s=1" 
... 

所不同的是陌生的,原因有二:1。 顯然CasperJS(其中坐在PhantomJS)JS運行之前不能返回HTML。這就是PhantomJS的全部要點。 2.我的解決方案都基於webkit

請注意,我也試着讓卡斯帕等5秒鐘(應該足夠的時間),以幫助排除waitForSelector行事有趣。鑑於這是一個非常簡單的測試案例,我希望有人能夠對結果爲什麼會有所不同。

謝謝!

回答

相關問題