簡體   English   中英

從href html標簽中提取鏈接(URL),在ruby中使用nokogiri?

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

我想從網頁中提取所有 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>

結果應該是一個列表:

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

你可以這樣做:

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 屬性。

好的,感謝 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