我正在使用Anemone蜘蛛一个域,它工作正常。
启动抓取的代码如下所示:
require 'anemone'
Anemone.crawl("http://www.example.com/") do |anemone|
anemone.on_every_page do |page|
puts page.url
end
end
这可以很好地打印出该域的所有页面网址,如下所示:
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“减去域”来创建一个键值对数组。
例如
[
['','/'],
['about','/about'],
['articles','/articles'],
['article_01','/articles/article_01']
]
抱歉,如果这是基本的东西,但我是 Ruby 新手。
最佳答案
我会首先在代码块之外定义一个数组或哈希,然后将键值对添加到其中:
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
从这里您可以将数组映射到可用的多维数组:
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 中使用和创建哈希的更多信息。
关于ruby - Anemone Ruby Spider - 创建无域名的键值数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19540989/