2013-11-01 51 views
1

你會如何獲得Facebook的喜歡,微博分享和谷歌1 +計數?如何使用ruby獲取/ share/1 +計數頁面?

對於example目前有78個贊,158個推文和21個1+。

我試着nokogiri颳去頁面的源,但問題是,這些東西在頁面加載後加載。

任何想法如何可以使用紅寶石獲得這些股票的計數?

回答

1

你應該使用可以處理Javascript的庫。

例如,下面是使用selenium-webdriver的溶液:

require 'selenium-webdriver' 

url = 'http://www.theverge.com/2013/10/31/5051682/' + 
     'googles-next-generation-nexus-5-android-4-4-kitkat-and-more' 

frame_count_selectors = [ 
    ['likes', '.fb_iframe_widget iframe', '.pluginCountTextDisconnected'], 
    ['tweets', 'iframe.twitter-tweet-button', '#count'], 
    ['+1s', '#___plusone_0 iframe', '#aggregateCount'], 
] 

driver = Selenium::WebDriver.for :firefox # :chrome/:phantomjs/... 
driver.get(url) 
frame_count_selectors.each do |name, frame_sel, count_sel| 
    driver.switch_to.default_content 
    frame = driver.find_element(:css, frame_sel) 
    driver.switch_to.frame frame 
    count = driver.find_element(:css, count_sel).text 
    puts "#{count} #{name}" 
end 
driver.quit 

輸出例如:

82 likes 
160 tweets 
21 +1s 
+0

感謝您的回答。我會在晚上嘗試這個解決方案。如果我要在AWS或Heroku上運行這個Ruby代碼,那麼我不能使用':firefox'?我應該在這種情況下使用':phantomjs'嗎? –

+0

@JasonKim,是的,'phantomjs'不需要你屏幕。但是你應該安裝[phantomjs](http://phantomjs.org/)。 – falsetru

相關問題