2015-07-28 58 views
0

我目前正在使用Ruby on Rails(Ruby:2.2.1,Rails:4.2.1)构建网站,并且想从特定的提取数据网站,然后显示它。我使用Nokogiri来获取网页内容。我正在寻找的是获取本网站的所有页面并获取他们的内容。如何使用Ruby on Rails获取特定网站的所有页面

下面我的代码:

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

你需要的代码是相当复杂的,你写的东西像它的1%。您基本上需要遍历页面上的所有链接,当您获取,过滤掉外部链接并存储已获取页面的数组时,以避免重复调用。 –

+0

您应该搜索堆栈溢出。这条线有很多问题。这里有一些指针:http://stackoverflow.com/a/4981595/128421 –

回答

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 
相关问题