从href html标记中提取链接(URL),并在ruby中使用nokogiri? [英] extract links (URLs), with nokogiri in ruby, from a href html tags?

查看:105
本文介绍了从href html标记中提取链接(URL),并在ruby中使用nokogiri?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从网页中提取所有URL,如何使用nokogiri?

I want to extract from a webpage all URLs how can I do that with 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选择器查​​找所有锚元素,并收集其href属性.

This solution finds all anchor elements using a css selector and collects their href attributes.

这篇关于从href html标记中提取链接(URL),并在ruby中使用nokogiri?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆