41

Web ページからすべての URL を抽出したいのですが、nokogiri でそれを行うにはどうすればよいですか?

例:

<div class="熱">
   <a href='http://example.org/site/1/'>サイト 1</a>
   <a href='http://example.org/site/2/'>サイト 2</a>
   <a href='http://example.org/site/3/'>サイト 3</a>
</div>

結果はリストでなければなりません:

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

4

2 に答える 2

87

次のように実行できます。

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 属性を収集します。

于 2009-05-13T09:01:34.693 に答える
8

sris のおかげで、このコードは私にとって完璧に機能します

p doc.xpath('//div[@class="heat"]/a').map { |リンク| リンク['href']}
于 2009-05-13T09:18:35.447 に答える