【问题标题】:extract links (URLs), with nokogiri in ruby, from a href html tags?从href html标签中提取带有红宝石中nokogiri的链接(URL)?
【发布时间】:2010-10-25 19:06:48
【问题描述】:

我想从网页中提取所有 URL,如何使用 nokogiri 来做到这一点?

示例:

结果应该是一个列表:

l = ['@987654321@', '@987654322@', '@987654323@'

【问题讨论】:

  • 有没有人有使用正则表达式的类似解决方案?速度有什么不同吗?

标签: ruby parsing nokogiri


【解决方案1】:

你可以这样做:

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 选择器查找所有锚元素并收集它们的 href 属性。

【讨论】:

  • 非常好,谢谢你拯救了我的一天 :) 一件事我现在从该网站获得了所有链接,但我只想要 div 中带有 clas “heat”的链接。这也可能吗?
  • 此示例是否也适用于

    中的任何链接而不是实时链接?

  • @AaronMoodie:是的,它适用于类 heat 的 div 中的任何链接。什么是实时链接?
【解决方案2】:

好的,感谢 sris,这段代码非常适合我

p doc.xpath('//div[@class="heat"]/a').map { |link|链接['href'] }

【讨论】:

    猜你喜欢
    • 2012-10-23
    • 2015-07-07
    • 2016-02-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-09
    • 1970-01-01
    • 1970-01-01
    • 2017-12-16
    相关资源
    最近更新 更多