我正在使用Anemone来爬取一个域,它工作得很好。
启动爬网的代码如下所示:
require 'anemone'
Anemone.crawl("http://www.example.com/") do |anemone|
anemone.on_every_page do |page|
puts page.url
end
end这将很好地打印出域的所有页面urls,如下所示:
http://www.example.com/
http://www.example.com/about
http://www.example.com/articles
http://www.example.com/articles/article_01
http://www.example.com/contact我想要做的是创建一个键值对数组,使用url的最后一部分作为键,而url减去domain作为值。
例如。
[
['','/'],
['about','/about'],
['articles','/articles'],
['article_01','/articles/article_01']
]如果这是最基本的东西,我很抱歉,但我是Ruby新手。
发布于 2013-10-23 20:33:46
我会首先在代码块之外定义一个数组或散列,然后将您的键值对添加到其中:
require 'anemone'
path_array = []
crawl_url = "http://www.example.com/"
Anemone.crawl(crawl_url) do |anemone|
anemone.on_every_page do |page|
path_array << page.url
puts page.url
end
end然后,您可以在此处将数组.map为可用的多维数组:
path_array.map{|x| [x[crawl_url.length..10000], x.gsub("http://www.example.com","")]}
=> [["", "/"], ["about", "/about"], ["articles", "/articles"], ["articles/article_01", "/articles/article_01"], ["contact", "/contact"]] 我不确定它是否在每个场景中都有效,但我认为这可以为您提供一个良好的开始,了解如何收集数据并对其进行操作。另外,如果你想要一个键/值对,你应该在Ruby的类Hash中找到更多关于如何在Ruby中使用和创建散列的信息。
发布于 2013-10-23 19:59:29
要做到这一点,最简单也可能是最不健壮的方法是使用
page.url.split('/').last来获取你的“钥匙”。您需要测试各种边缘用例,以确保它可靠地工作。
编辑:这将返回'www.example.com‘作为'http://www.example.com/’的键,这不是您需要的结果
https://stackoverflow.com/questions/19540989
复制相似问题