找到页面中最大的表格

时间:2011-01-31 15:19:02

标签: ruby nokogiri

有人可以告诉我如何使用Nokogiri找到网页中最大的表格(即行数最多的表格)吗?可以使用Lambda函数完成吗?

3 个答案:

答案 0 :(得分:2)

biggest_table = doc.xpath('//table').max_by do |table|
  table.xpath('.//tr').length
end

或者,如果存在平局,也许您需要一个包含最多行的所有表的列表:

# Hash mapping number of rows to array of table nodes
tables = doc.xpath('//table').group_by{ |t| t.xpath('.//tr').length }

# Array of all (possibly only 1) tables with the most rows
biggest_n = tables[table.keys.max]

答案 1 :(得分:0)

这可能不是您想要的,但您可以使用jQuery或Prototype在浏览器上轻松完成此操作。

答案 2 :(得分:0)

tables = @doc.xpath('//table')
tr_count = tables.map{|n| n.xpath('tr|*/tr').length}
biggest_table = tables[tr_count.index(tr_count.max)]
相关问题