有没有办法通过使用符号键而不是字符串键来访问 Nokogiri::XML::Attr
Is there a way to access Nokogiri::XML::Attr by using a symbol key, not a string key
我有这样的代码
require 'nokogiri'
url = ENV['URL']
doc = Nokogiri::HTML(open(url))
link = doc.css('a#foo').attr('href').value
我想使用这样的符号访问 Nokogiri::XML::Attr
。
doc = Nokogiri::HTML(open(url), hash_key_symbol: true)
link = doc.css('a#foo').attr(:href).value
我找不到相关信息,但也许我忽略了它。
有这样的选项吗?
您正在调用 attr
on the NodeSet
returned from css
, not on a single Node
object. attr
on a Node
will accept a symbol to specify the attribute, and has done for a while,但似乎没有对 NodeSet#attr
进行相应的更改。请注意,attr
的 NodeSet
版本用于在集合中的所有节点上设置属性,并且只会 return first[= 上的属性值31=] 如果不指定值,它包含的节点。
您可以使用 at_css
明确地只 select 您查询的第一个匹配节点,然后您可以使用一个符号:
doc.at_css('a#foo').attr(:href).value
或者,您可以 select 来自由其索引设置的节点的节点:
doc.css('a#foo')[0].attr(:href).value
访问标记中参数的简单方法是使用 "hash" []
语法:
require 'nokogiri'
html = <<EOT
<html>
<body>
<a href="blah" id="foo">bar</a>
</body>
</html>
EOT
doc = Nokogiri::HTML(html)
doc.at('a#foo')['href'] # => "blah"
但是我们可以用一个符号:
doc.at('a#foo')[:href] # => "blah"
注意,at
等同于search('a#foo').first
,return都是一个节点。 search
及其 CSS 和 XPath 变体 return NodeSets,它们不具备 return 特定节点或所有节点的属性的能力。要处理多个节点,请使用 map
:
html = <<EOT
<html>
<body>
<a href="blah" class="foo">bar1</a>
<a href="more_blah" class="foo">bar2</a>
</body>
</html>
EOT
doc = Nokogiri::HTML(html)
doc.search('a.foo').map{ |n| n['href'] } # => ["blah", "more_blah"]
我有这样的代码
require 'nokogiri'
url = ENV['URL']
doc = Nokogiri::HTML(open(url))
link = doc.css('a#foo').attr('href').value
我想使用这样的符号访问 Nokogiri::XML::Attr
。
doc = Nokogiri::HTML(open(url), hash_key_symbol: true)
link = doc.css('a#foo').attr(:href).value
我找不到相关信息,但也许我忽略了它。 有这样的选项吗?
您正在调用 attr
on the NodeSet
returned from css
, not on a single Node
object. attr
on a Node
will accept a symbol to specify the attribute, and has done for a while,但似乎没有对 NodeSet#attr
进行相应的更改。请注意,attr
的 NodeSet
版本用于在集合中的所有节点上设置属性,并且只会 return first[= 上的属性值31=] 如果不指定值,它包含的节点。
您可以使用 at_css
明确地只 select 您查询的第一个匹配节点,然后您可以使用一个符号:
doc.at_css('a#foo').attr(:href).value
或者,您可以 select 来自由其索引设置的节点的节点:
doc.css('a#foo')[0].attr(:href).value
访问标记中参数的简单方法是使用 "hash" []
语法:
require 'nokogiri'
html = <<EOT
<html>
<body>
<a href="blah" id="foo">bar</a>
</body>
</html>
EOT
doc = Nokogiri::HTML(html)
doc.at('a#foo')['href'] # => "blah"
但是我们可以用一个符号:
doc.at('a#foo')[:href] # => "blah"
注意,at
等同于search('a#foo').first
,return都是一个节点。 search
及其 CSS 和 XPath 变体 return NodeSets,它们不具备 return 特定节点或所有节点的属性的能力。要处理多个节点,请使用 map
:
html = <<EOT
<html>
<body>
<a href="blah" class="foo">bar1</a>
<a href="more_blah" class="foo">bar2</a>
</body>
</html>
EOT
doc = Nokogiri::HTML(html)
doc.search('a.foo').map{ |n| n['href'] } # => ["blah", "more_blah"]