2011-11-22 97 views
1
@p = mechanize.get(url) 
tables = @p.search('table.someclass') 

我基本上会在大约200页,将表中的数组和排序的唯一方法是找到与表最多的行数。查找表和机械化

所以我想能够看看数组中的每个项目,并选择行数最多的第一个项目。

我一直在尝试使用max_by,但这不起作用,因为我需要搜索数组项目表,以查找tr.count。

回答

1

两种方式:

biggest = tables.max_by{ |table| table.css('tr').length } 
biggest = tables.max_by{ |table| table.xpath('.//tr').length } 

因为你没举一个例子网址,这里是表明max_by可以使用类似的搜索:

require 'mechanize' 
mechanize = Mechanize.new 
rows = mechanize.get("http://phrogz.net/").search('table#infoporn tbody tr') 

# Find the table row from the array that has the longest link URL in it 
biggest = rows.max_by{ |tr| tr.at_xpath('.//a/@href').text.length } 

p biggest.name, biggest.at('.//a/@href') 
#=> "tr" 
#=> [#<Nokogiri::XML::Attr:0x1681680 name="href" value="slow-file-reads-on-windows-ruby-1.9">] 
+0

感谢Phrogz,这是伟大的。 – user1010100