使用 Nokogiri & 从 html doc 获取链接和 href 文本红宝石? [英] Get link and href text from html doc with Nokogiri & Ruby?

查看:44
本文介绍了使用 Nokogiri & 从 html doc 获取链接和 href 文本红宝石?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 nokogiri gem 提取页面上的所有 url 及其链接文本,并将链接文本和 url 存储在哈希中.

I'm trying to use the nokogiri gem to extract all the urls on the page as well their link text and store the link text and url in a hash.

<html>
    <body>
        <a href=#foo>Foo</a>
        <a href=#bar>Bar </a>
    </body>
</html>

我想回来

{"Foo" => "#foo", "Bar" => "#bar"}

推荐答案

这里是单行:

Hash[doc.xpath('//a[@href]').map {|link| [link.text.strip, link["href"]]}]

#=> {"Foo"=>"#foo", "Bar"=>"#bar"}

拆分一点可以说更具可读性:

Split up a bit to be arguably more readable:

h = {}
doc.xpath('//a[@href]').each do |link|
  h[link.text.strip] = link['href']
end
puts h

#=> {"Foo"=>"#foo", "Bar"=>"#bar"}

这篇关于使用 Nokogiri &amp; 从 html doc 获取链接和 href 文本红宝石?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆