extraer enlaces (URLs), con nokogiri en ruby, de un href etiquetas html?


Quiero extraer de una página web todas las URL ¿cómo puedo hacer eso con nokogiri?

Ejemplo:

<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>

El resultado debe ser una lista:

l = ['http://example.org/site/1/', 'http://example.org/site/2/', 'http://example.org/site/3/'
Author: gustavgans, 2009-05-13

2 answers

Puedes hacerlo así:

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'] }

Esta solución encuentra todos los elementos de anclaje utilizando un selector css y recoge sus atributos href.

 75
Author: sris,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-05-13 09:19:32

Ok este código funciona perfecto para mí, gracias a sris

p doc.xpath('//div[@class="heat"]/a').map { |link| link['href'] }
 8
Author: gustavgans,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-05-13 09:18:35