gpt4 book ai didi

ruby - Anemone Ruby spider - 创建没有域名的键值数组

转载 作者:太空宇宙 更新时间:2023-11-03 16:03:28 24 4
gpt4 key购买 nike

我正在使用 Anemone爬取一个域,它工作正常。

启动抓取的代码如下所示:

require 'anemone'

Anemone.crawl("http://www.example.com/") do |anemone|
anemone.on_every_page do |page|
puts page.url
end
end

这非常好地打印出域的所有页面 url,如下所示:

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com