在 nokogiri 中获取标签的实例编号
Get instance no of a tag in nokogiri
我想获取实例号。标签的,即 - 给定节点是否是给定标签的第一个、第二个或第三个等实例。
例如,如果我在节点上调用 node.path
,我会得到以下输出:
/html/head/base/link/body/div/br/form/hr/chapter[1]/section[1]/ul/li[1]/a
如何获得 section
旁边的 1?
require 'nokogiri'
html_string=<<END
<html>
<body>
<div>
<span></span>
<span></span>
<span></span>
<span>
<h1></h1>
</span>
<span></span>
<span>
<strong></strong>
</span>
<span></span>
<span></span>
</div>
</body>
</html>
END
doc = Nokogiri::HTML(html_string)
h1 = doc.xpath("/html/body/div/span/h1")[0]
puts h1.path # output => /html/body/div/span[4]/h1
puts h1.parent.xpath("preceding-sibling::*").size + 1 # output => 4
strong = doc.xpath("/html/body/div/span/strong")[0]
puts strong.path # output => /html/body/div/span[6]/strong
puts strong.parent.xpath("preceding-sibling::*").size + 1 # output => 6
我想获取实例号。标签的,即 - 给定节点是否是给定标签的第一个、第二个或第三个等实例。
例如,如果我在节点上调用 node.path
,我会得到以下输出:
/html/head/base/link/body/div/br/form/hr/chapter[1]/section[1]/ul/li[1]/a
如何获得 section
旁边的 1?
require 'nokogiri'
html_string=<<END
<html>
<body>
<div>
<span></span>
<span></span>
<span></span>
<span>
<h1></h1>
</span>
<span></span>
<span>
<strong></strong>
</span>
<span></span>
<span></span>
</div>
</body>
</html>
END
doc = Nokogiri::HTML(html_string)
h1 = doc.xpath("/html/body/div/span/h1")[0]
puts h1.path # output => /html/body/div/span[4]/h1
puts h1.parent.xpath("preceding-sibling::*").size + 1 # output => 4
strong = doc.xpath("/html/body/div/span/strong")[0]
puts strong.path # output => /html/body/div/span[6]/strong
puts strong.parent.xpath("preceding-sibling::*").size + 1 # output => 6