从href html标签中提取链接(URL),使用红宝石中的nokogiri?

gus*_*ans 39 ruby parsing nokogiri

我想从网页中提取所有网址,我怎么能用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/'

sri*_*ris 80

你可以这样做:

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'] }
Run Code Online (Sandbox Code Playgroud)

此解决方案使用css选择器查​​找所有锚元素并收集其href属性.


gus*_*ans 8

好吧,这个代码对我来说非常适合,感谢sris

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