Table对象是自动化测试中经常需要处理的对象。由于webdriver中没有专门的table类,所以我们需要简单的封装出一个易用易扩展的Table类来帮助简化代码。
module EasyWrap class EasyWrapError < StandardError;end class NotValidElementError < EasyWrapError;end class IncorrectdIndexError < EasyWrapError;end class TableBase attr_reader :e def initialize e raise NotValidElementError unless e.is_a?(Selenium::WebDriver::Element) @e = e end def method_missing(m, *params, &blk) @e.send(m, *params) if @e.respond_to?(m) end end #TableBase class Table < TableBase def initialize e super(e) __rows end def __rows @rows = @e.find_elements(:css => 'tr') end private :__rows def rows all_rows = [] @rows.each { |r| rows << TableRow.new(r)} all_rows end def row_count @rows.size end def [](index) valid_index? index TableRow.new @rows[index] end def valid_index?(index) raise IncorrectdIndexError if index.to_i > row_count end end #Table class TableRow < TableBase def initialize e super(e) __cells end def __cells @cells = @e.find_elements(:tag_name => 'td') # 如果找不到td那么试着去找th @cells = @e.find_elements(:tag_name => 'th') if @cells.empty? end private :__cells def cells all_cells = [] @cells.each {|c| all_cells << TableCell.new(c)} end def cell_count @cells.size end def [](index) valid_index? index TableCell.new @cells[index] end def valid_index?(index) raise IncorrectdIndexError if index.to_i > cell_count end end #TableRow class TableCell < TableBase end #TableCellend #EasyWrap
EasyWrap定义了3个类
-
Table类,代表1个table对象,可以通过该对象来访问该table的行和列;
-
TableRow类 代表table的某1行,可以通过其访问table的某一列;
-
TableCell类 代表table的某1个单元格
假如我们需要点击table的第3行第1列,通过EasyWrap,我们可以这样来实现
talbe = EasyWrap::Table(dr.find_element(:id => 'table_id'))table[2][0].click
以下面的html代码为例:
Table
C1 | C2 | C3 |
---|---|---|
v1 | v2 | v3 |
k1 | k2 | k3 |
接下来的脚本实现了高亮页面上table元素首行首列的功能
require 'rubygems'require 'selenium-webdriver'require './easy_wrap'include EasyWrap dr = Selenium::WebDriver.for :firefoxtable_file = 'file:///'+File.expand_path(File.join(File.dirname(__FILE__), 'table.html'))dr.get table_filet = dr.find_element(:id => 't')table = Table.new tp table.row_counthighlight = <