0
task :fetch_front => :environment do 
require 'rubygems' 
require 'nokogiri' 
require 'open-uri' 
require 'mechanize' 
    agent = Mechanize.new 

    agent.get("http://www.reddit.com/") 

    agent.page.search("a.title").each do |thread| 
    thread.click 

    end 
end 

我正在使用mechanize進入第一頁上的每個reddit線程並返回每個線程的頂級註釋。每個方法中的'線程'塊返回每個reddit線程的鏈接。問題是我不知道如何點擊進入線程並返回每個線程的頂端評論未定義的方法錯誤click for simple webscraper

使用我當前的代碼,當我嘗試單擊每個線程以顯示註釋時,它將返回undefined method click錯誤。在代理

回答

0

呼叫click並傳遞要點擊作爲參數的東西:

agent.click(thread) 
0

點擊主題標題並不總是帶你到螺紋評論頁面。可以肯定的是,您必須點擊具有線索評論數量的鏈接。我寫了(和測試),這個代碼將帶你到每個線程評論頁面。

require 'mechanize' 
robot = Mechanize.new 
response = robot.get('http://www.reddit.com/').parser 

# Get the comments page link for every thread on the first page 
response.css('#siteTable .thing a.comments').each do |thread_comments_link| 
    comments_page = robot.get(thread_comments_link[:href]).parser 
    # scrap comments page here 
end 

注:當您使用mechanize你不必要求nokogiriopen-uri。 Nokogiri是一個機械化的運行時間依賴,所以機械化將需要它,並且open-uri不是必需的。