Ruby-on-rails 在 Nokogiri 中获取属性值以提取链接 URL
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7107642/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Getting attribute's value in Nokogiri to extract link URLs
提问by Kreeki
I have a document which look like this:
我有一个看起来像这样的文件:
<div id="block">
<a href="http://google.com">link</a>
</div>
I can't get Nokogiri to get me the value of hrefattribute. I'd like to store the address in a Ruby variable as a string.
我无法让 Nokogiri 为我获取href属性值。我想将地址作为字符串存储在 Ruby 变量中。
回答by Michael Kohl
html = <<HTML
<div id="block">
<a href="http://google.com">link</a>
</div>
HTML
doc = Nokogiri::HTML(html)
doc.xpath('//div/a/@href')
#=> [#<Nokogiri::XML::Attr:0x80887798 name="href" value="http://google.com">]
Or if you wanna be more specific about the div:
或者,如果您想更具体地了解 div:
>> doc.xpath('//div[@id="block"]/a/@href')
=> [#<Nokogiri::XML::Attr:0x80887798 name="href" value="http://google.com">]
>> doc.xpath('//div[@id="block"]/a/@href').first.value
=> "http://google.com"
回答by seldomatt
doc = Nokogiri::HTML(open("[insert URL here]"))
href = doc.css('#block a')[0]["href"]
The variable hrefis assigned to the value of the "href"attribute for the <a>element inside the element with id 'block'. The line doc.css('#block a')returns a single item array containing the attributes of #block a. [0]targets that single element, which is a hash containing all the attribute names and values. ["href"]targets the key of "href"inside that hash and returns the value, which is a string containing the url.
该变量href被分配给id 元素内元素的"href"属性值。该行返回包含 的属性的单个项目数组。 以单个元素为目标,它是一个包含所有属性名称和值的哈希。 以该哈希内部的键为目标并返回值,该值是一个包含 url 的字符串。 <a>'block'doc.css('#block a')#block a[0]["href"]"href"
回答by fearless_fool
Having struggled with this question in various forms, I decided to write myself a tutorial disguised as an answer. It may be helpful to others.
在以各种形式与这个问题作斗争之后,我决定给自己写一个伪装成答案的教程。它可能对其他人有帮助。
Starting with with this snippet:
从这个片段开始:
require 'rubygems'
require 'nokogiri'
html = <<HTML
<div id="block1">
<a href="http://google.com">link1</a>
</div>
<div id="block2">
<a href="http://stackoverflow.com">link2</a>
<a id="tips">just a bookmark</a>
</div>
HTML
doc = Nokogiri::HTML(html)
extracting all the links
提取所有链接
We can use xpath or css to find all the elements and then keep only the ones that have an hrefattribute:
我们可以使用 xpath 或 css 来查找所有元素,然后只保留具有href属性的元素:
nodeset = doc.xpath('//a') # Get all anchors via xpath
nodeset.map {|element| element["href"]}.compact # => ["http://google.com", "http://stackoverflow.com"]
nodeset = doc.css('a') # Get all anchors via css
nodeset.map {|element| element["href"]}.compact # => ["http://google.com", "http://stackoverflow.com"]
But there's a better way: in the above cases, the .compactis necessary because the searches return the "just a bookmark" element as well. We can use a more refined search to find just the elements that contain an hrefattribute:
但是有更好的方法:在上述情况下,这.compact是必要的,因为搜索也返回“只是书签”元素。我们可以使用更精细的搜索来仅查找包含href属性的元素:
attrs = doc.xpath('//a/@href') # Get anchors w href attribute via xpath
attrs.map {|attr| attr.value} # => ["http://google.com", "http://stackoverflow.com"]
nodeset = doc.css('a[href]') # Get anchors w href attribute via css
nodeset.map {|element| element["href"]} # => ["http://google.com", "http://stackoverflow.com"]
finding a specific link
查找特定链接
To find a link within the <div id="block2">
要在其中找到链接 <div id="block2">
nodeset = doc.xpath('//div[@id="block2"]/a/@href')
nodeset.first.value # => "http://stackoverflow.com"
nodeset = doc.css('div#block2 a[href]')
nodeset.first['href'] # => "http://stackoverflow.com"
If you know you're searching for just one link, you can use at_xpathor at_cssinstead:
如果您知道只搜索一个链接,则可以使用at_xpath或at_css代替:
attr = doc.at_xpath('//div[@id="block2"]/a/@href')
attr.value # => "http://stackoverflow.com"
element = doc.at_css('div#block2 a[href]')
element['href'] # => "http://stackoverflow.com"
find a link from associated text
从相关文本中查找链接
What if you know the text associated with a link and want to find its url? A little xpath-fu (or css-fu) comes in handy:
如果您知道与链接相关联的文本并想找到它的 url 怎么办?一个小 xpath-fu(或 css-fu)派上用场:
element = doc.at_xpath('//a[text()="link2"]')
element["href"] # => "http://stackoverflow.com"
element = doc.at_css('a:contains("link2")')
element["href"] # => "http://stackoverflow.com"
find text from a link
从链接中查找文本
And what if you want to find the text associated with a particular link? Not a problem:
如果您想查找与特定链接关联的文本怎么办?不是问题:
element = doc.at_xpath('//a[@href="http://stackoverflow.com"]')
element.text # => "link2"
element = doc.at_css('a[href="http://stackoverflow.com"]')
element.text # => "link2"
useful references
有用的参考
In addition to the extensive Nokorigi documentation, I came across some useful links while writing this up:
除了大量的Nokorigi 文档外,我在写这篇文章时还发现了一些有用的链接:
回答by bor1s
doc = Nokogiri::HTML("HTML ...")
href = doc.css("div[id='block'] > a")
result = href['href'] #http://google.com
回答by Gagan Gami
data = '<html lang="en" class="">
<head>
<a href="https://example.com/9f40a.css" media="all" rel="stylesheet" /> link1</a>
<a href="https://example.com/4e5fb.css" media="all" rel="stylesheet" />link2</a>
<a href="https://example.com/5s5fb.css" media="all" rel="stylesheet" />link3</a>
</head>
</html>'
Here is my Try for above sample of HTML code:
这是我对上述 HTML 代码示例的尝试:
doc = Nokogiri::HTML(data)
doc.xpath('//@href').map(&:value)
=> [https://example.com/9f40a.css, https://example.com/4e5fb.css, https://example.com/5s5fb.css]
回答by Oscar Albert
document.css("#block a")["href"]
where documentis the Nokogiri HTML parsed.
documentNokogiri HTML在哪里解析。

