使用 Nokogiri & 从 html 文档获取链接和 href 文本红宝石?
我正在尝试使用 nokogiri gem 提取页面上的所有 url 及其链接文本,并将链接文本和 url 存储在哈希中。
<html>
<body>
<a href=#foo>Foo</a>
<a href=#bar>Bar </a>
</body>
</html>
我想回来
{"Foo" => "#foo", "Bar" => "#bar"}
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>
I would like to return
{"Foo" => "#foo", "Bar" => "#bar"}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是一句俏皮话:
分开一点可以说更具可读性:
Here's a one-liner:
Split up a bit to be arguably more readable:
另一种方式:
如果您担心相同的文本可能会链接到不同的内容,那么您可以将
href
收集到数组中:Another way:
And if you're worried that you might have the same text linking to different things then you collect the
href
s in arrays: