2011-11-22 93 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