我想从一个网页中提取所有的URL我怎么能用nokogiri做到这一点?

例子:

<div class="heat">
   <a href='http://example.org/site/1/'>site 1</a>
   <a href='http://example.org/site/2/'>site 2</a>
   <a href='http://example.org/site/3/'>site 3</a>
</diV>

结果应该是一个列表:

l = ['http://example.org/site/1/', 'http://example.org/site/2/', 'http://example.org/site/3/'

推荐答案

你可以这样做:

doc = Nokogiri::HTML.parse(<<-HTML_END)
<div class="heat">
   <a href='http://example.org/site/1/'>site 1</a>
   <a href='http://example.org/site/2/'>site 2</a>
   <a href='http://example.org/site/3/'>site 3</a>
</div>
<div class="wave">
   <a href='http://example.org/site/4/'>site 4</a>
   <a href='http://example.org/site/5/'>site 5</a>
   <a href='http://example.org/site/6/'>site 6</a>
</div>
HTML_END

l = doc.css('div.heat a').map { |link| link['href'] }

此解决方案使用css Select 器查找所有锚元素,并收集它们的href属性.

Ruby相关问答推荐

Ruby:对于不存在的键,使用缺省值Hash在Hash中存储Hash

PDFNet:Ubuntu 16.04 和 Ubuntu 20.04 上 PDF 输出文本的词序不同

while 语句的主体是块吗?

ruby 中的魔术注释(#Encoding: utf-8)是如何工作的?

Ruby vs Scala - 各自的优缺点

如何在 Ruby 中生成子进程?

Ruby on Rails:你能把 Ruby 代码放在 YAML 配置文件中吗?

如何拯救 Ruby 中的 eval?

ruby中字符的整数值?

Ruby 中的排序稳定吗?

如何绘制 git repo 的代码行历史记录?

就地修改 ruby​​ 哈希(rails strong params)

Sinatra 登录?

通过 x 个字符在 Ruby 中获取子字符串

rbenv、rvm 和 chruby 有什么区别?

计算文件中的行数而不将整个文件读入内存?

在 Ruby 中, coerce() 是如何工作的?

如何使用 Ruby-Rails 删除文件夹的所有内容?

从 'mm/dd/yyyy' 格式解析 ruby​​ DateTime

Ruby 中的那些管道符号是什么?