【问题标题】:Nokogiri in Rails - Scrape results of multiple pagesRails 中的 Nokogiri - 抓取多个页面的结果
【发布时间】:2014-06-03 09:08:14
【问题描述】:

我在 Rails 中使用 Nokogiri,同时尝试从 Subreddit 的多个页面获取结果,但我只能获取第一页。关于如何实现这一点的任何想法。我似乎无法弄清楚这一点。这是我目前的 RedditScraper 课程:

require 'nokogiri'
require 'open-uri'

class RedditScraper

def initialize
 @headline = []
end

def fetch_reddit_headlines
 page = Nokogiri::HTML(open("http://www.reddit.com/r/ruby"))
 page.css('a.title').each do |link|
   if link['href'].include?('http')
    @headline << { content: link.content, href: link['href'] }
   else
    @headline << { content: link.content, href: "http://reddit.com" + link['href'] }
   end
  end
  @headline
 end
end

刚刚添加

控制器方法:

def index
 @fetch_reddit = RedditScraper.new.fetch_reddit_headlines    
end

查看代码:

<ol>
 <% @fetch_reddit.each do |url| %>
  <li><%= link_to url[:content], url[:href], target: '_' %></li>
 <% end %>
</ol>

截图

【问题讨论】:

    标签: ruby-on-rails web-scraping nokogiri


    【解决方案1】:

    如果您将Mechanize 与 Nokogiri 一起使用,您可以通过执行以下操作单击下一页链接:

    更新:修复了一些错误

    require 'nokogiri'
    require 'open-uri'
    require 'mechanize'
    
    
    class RedditScraper
    
      def initialize
        @headline = []
        @agent = Mechanize.new
      end
    
      def fetch_reddit_headlines
        mech_page = @agent.get('http://www.reddit.com/r/ruby')
    
        num_pages_to_scrape = 10
        count = 0
    
        while(num_pages_to_scrape > count)
          page = mech_page.parser
    
          page.css('a.title').each do |link|
            if link['href'].include?('http')
              @headline << { content: link.content, href: link['href'] }
            else
              @headline << { content: link.content, href: "http://reddit.com" + link['href'] }
            end
          end
          @headline
    
          count += 1
          mech_page = @agent.get(page.css('.nextprev').css('a').last.attributes["href"].value)
        end
    
        return @headline
      end
    end
    
    
    r = RedditScraper.new
    r.fetch_reddit_headlines
    puts r.instance_variable_get(:@headline)
    puts r.instance_variable_get(:@headline).count
    

    【讨论】:

    • 我尝试了代码,但现在收到了上面的消息(请参阅更新的问题)
    • @Chip - 我更新了我的代码。只需要在函数末尾返回@headline 变量。看底部fetch_reddit_headlines
    • @Chip 您可能希望将标题存储在数据库记录中。这比为每个请求抓取网页要快得多。如果您需要帮助,请告诉我:)
    • 谢谢马特。我将如何将它们存储在数据库记录中?我正在使用 pg。
    • @Chip - 给我发一封电子邮件至 mattleonardco@gmail.com,我们可以在那里讨论。需要有关您的应用的更多信息。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-03
    • 1970-01-01
    • 2019-05-12
    • 1970-01-01
    相关资源
    最近更新 更多