如何使用Ruby on Rails获取特定网站的所有页面

时间:2015-07-28 10:16:12

标签: ruby-on-rails ruby nokogiri

我目前正在使用Ruby on Rails(Ruby:2.2.1,Rails:4.2.1)构建一个网站,并希望从特定网站提取数据然后显示它。我使用Nokogiri获取网页内容。我正在寻找的是获取本网站的所有页面并获取其内容。

在我的代码下面:

doc = Nokogiri::HTML(open("www.google.com").read)
puts doc.at_css('title').text
puts doc.to_html

1 个答案:

答案 0 :(得分:0)

这是您所需要的非常近似的要点:

class Parser
  attr_accessor :pages

  def fetch_all(host)
    @host = host

    fetch(@host)
  end

  private

  def fetch(url)
    return if pages.any? { |page| page.url == url }
    parse_page(Nokogiri::HTML(open(url).read))
  end

  def parse_page(document)
    links = extract_links(document)

    pages << Page.new(
      url: url,
      title: document.at_css('title').text,
      content: document.to_html,
      links: links
    )

    links.each { |link| fetch(@host + link) }
  end

  def extract_links(document)
    document.css('a').map do |link|
      href = link['href'].gsub(@host, '')
      href if href.start_with?('/')
    end.compact.uniq
  end
end

class Page
  attr_accessor :url, :title, :html_content, :links

  def initialize(url:, title:, html_content:, links:)
    @url = url
    @title = title
    @html_content = html_content
    @links = links
  end
end