извлекать ссылки (URL), используя nokogiri в ruby, из href html тэгов? - PullRequest
39 голосов
/ 13 мая 2009

Я хочу извлечь из веб-страницы все 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>

Результатом должен быть список:

<code>l = ['<a href="http://example.org/site/1/" rel="noreferrer">http://example.org/site/1/</a>', '<a href="http://example.org/site/2/" rel="noreferrer">http://example.org/site/2/</a>', '<a href="http://example.org/site/3/" rel="noreferrer">http://example.org/site/3/</a>'

Ответы [ 2 ]

79 голосов
/ 13 мая 2009

Вы можете сделать это так:

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.

8 голосов
/ 13 мая 2009

хорошо, этот код отлично работает для меня, благодаря sris

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