计算此div中的表数

时间:2016-06-07 11:23:23

标签: html ruby

嗨我相对较新的html和ruby。我有一个div,它有5个表,每个表有相同的类。我想计算这个div中的表数,但它只返回1个表。

我试过了 puts @ browser.div(:id =>" pricingChildrenValuesJWPDIV")。table.rows.length

html elements

我怎样才能找到这个表的总数:div please,thanks

1 个答案:

答案 0 :(得分:0)

您可以将NokogiriXPath

一起使用

就像这个例子:

require 'nokogiri'

html_s = '<html>
<div id="pricingChildrenValuesJWPDIV">
<table id="one"></table>
<table id="two"></table>
<table id="three"></table>
</div>
<div id="none">
<table id="one"></table>
<table id="two"></table>
</div>
</html>'

# Parsing HTML document to Nokogiri::HTML::Document
html_doc = Nokogiri::HTML(html_s)

# Use XPath to find all elements (div) with attributes id with value pricingChildrenValuesJWPDIV
# and tables inside this element
tables = html_doc.xpath("//div[@id='pricingChildrenValuesJWPDIV']/table")
# get size of those elements
tables.size
# => 3

# Use XPath to find all elements (div) with attributes id with value none
# and tables inside this element
tables = html_doc.xpath("//div[@id='none']/table")
# get size of those elements
tables.size
# => 2

# Use XPath to find all elements (div) with attributes id with value foo
# and tables inside this element
tables = html_doc.xpath("//div[@id='foo']/table")
# get size of those elements
tables.size
# => 0

我希望这会有所帮助