2012-11-07 66 views
3

我有一些网站,例如http://example.com
我要生成一个网站地图为URI的列表,如:站点地图生成器上的Ruby

  • http://example.com/main
  • http://example.com/tags
  • http://example.com/tags/foo
  • http://example.com/tags/bar

我发现它的一个很好的应用:iGooMap
iGooMap可以生成所需的URI列表作为文本文件(而不是XML文件)。
这里是什么,我想实现的可视化表示:

Here is what I would like to have

我想有这种类型的红宝石( Rails)的生成网站地图的。
我找到了SiteMapGenerator,但它只生成一个.XML文件,但是据说我需要一个文本文件。

是否有解决方案的Ruby创建一个给定的网站的链接列表?

回答

6

你想要的是不是在Ruby 站点地图生成器,但一个web蜘蛛在Ruby中。我建议Anemone

require 'anemone' 

links = [] 

Anemone.crawl("http://www.foo.com/") do |anemone| 
    anemone.on_every_page do |page| 
     links << page.url 
    end 
end 

File.open('./link_list.txt', 'wb'){|f| f.write links.join("\n") } 

这会产生一个名为link_list.txt与文件,内容如下:

http://www.foo.com/ 
http://www.foo.com/digimedia_privacy_policy.html 

还有WombatSpidrPioneer等等。


编辑:正如@ChrisCummings暗示,它可能是一个更好的主意,以防止重复使用Set而不是Array。我还建议按字母顺序排序的链接,这将使输出文件更易于阅读的人:

require 'anemone' 
require 'set' 

links = Set.new         # Set will prevent duplicates 

Anemone.crawl("http://www.foo.com/") do |anemone| 
    anemone.on_every_page do |page| 
    links << page.url.to_s       # to_s needed in order to sort 
    end 
end 

File.open('./link_list.txt', 'wb') do |f| 
    f.write links.sort.join("\n")     # call to sort added 
end 
+0

这杯绅士两杯茶! 这正是我所期待的。 非常感谢! –

+0

不客气;-) –

+0

我会使用Set而不是Array作为我的集合类,以避免重复的URL。 http://www.ruby-doc.org/stdlib-2.0.0/libdoc/set/rdoc/Set.html –

3

您可以用自定义适配器扩展sitemap_generator,例如:

require 'sitemap_generator' 
require 'nokogiri' 

module SitemapGenerator 
    class TextFileAdapter 
    def write(location, raw_data) 
     # Ensure that the directory exists 
     dir = location.directory 
     if !File.exists?(dir) 
     FileUtils.mkdir_p(dir) 
     elsif !File.directory?(dir) 
     raise SitemapError.new("#{dir} should be a directory!") 
     end 

     doc = Nokogiri::XML(raw_data) 
     txt = doc.css('url loc').map(&:text).join("\n") 

     open(location.path, 'wb') do |f| 
     f.write(txt) 
     end 
    end 
    end 
end 

SitemapGenerator::Sitemap.default_host = 'http://example.com' 
SitemapGenerator::Sitemap.create(
    :adapter => SitemapGenerator::TextFileAdapter.new, 
    :sitemaps_namer => SitemapGenerator::SitemapNamer.new(:sitemap, :extension => '.txt') 
) do 
    add '/home', :changefreq => 'daily', :priority => 0.9 
    add '/contact_us', :changefreq => 'weekly' 
end 
SitemapGenerator::Sitemap.ping_search_engines 

这导致文件public/sitemap1.txt

http://example.com 
http://example.com/home 
http://example.com/contact_us 
+0

日Thnx,但我需要添加所有的URI中的“添加‘/%瓮%’,:的changefreq =>‘周’ “模板? 我需要从文本文件中自动生成所有uri文件。 –

+0

示例:网站有两个页面。/foo,/ bar。 /foo页面有连接到/ bar页面。 <! - file /foo.html - > Bar 我需要站点地图。txt与下一个来源: http://example.com/foo/ http://example.com/bar/ 这种情况下也称为“蜘蛛”。 –

+0

请看我的第二个答案。 –