简体   繁体   English

从href html标签中提取链接(URL),在ruby中使用nokogiri?

[英]extract links (URLs), with nokogiri in ruby, from a href html tags?

I want to extract from a webpage all URLs how can I do that with nokogiri?我想从网页中提取所有 URL,我该如何使用 nokogiri 来做到这一点?

example:例子:

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

result should be an list:结果应该是一个列表:

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

You can do it like this:你可以这样做:

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

This solution finds all anchor elements using a css selector and collects their href attributes.此解决方案使用 css 选择器查找所有锚元素并收集它们的 href 属性。

ok this code works perfect for me, thanks to sris好的,感谢 sris,这段代码非常适合我

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM