这是你需要什么是非常近似的要点是:
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
你需要的代码是相当复杂的,你写的东西像它的1%。您基本上需要遍历页面上的所有链接,当您获取,过滤掉外部链接并存储已获取页面的数组时,以避免重复调用。 –
您应该搜索堆栈溢出。这条线有很多问题。这里有一些指针:http://stackoverflow.com/a/4981595/128421 –