兆鹏带你读watir——【第三篇】元素定位的过程

大家都会在N多网站上发现有讲解watir元素定位的方法,但是只是表面,而忽略了定位的整体流程,本篇介绍元素定位的流程!


需要读的文件:lib\watir\element.rb , input_element.rb,  locator.rb , container.rb

以一个例子讲解整个定位流程,例子如下:

ie=Watir::IE.new
ie.goto 'image.baidu.com'
ie.text_field(:class,'kw').set 'robin'
在IE-CLASS.RB中 include Container的模块,在ie-class.rb文件的头几行有如下代码:

module Watir
  class IE
    include WaitHelper
    include Exception
    include Container
    include PageContainer
因此,现在ie-class.rb中有了container.rb中Module Container中的函数啦!

所以才可以用ie.text_field(:class,'kw')这样去定位

接下来看Container.rb中Module Container中的函数方法

    def text_field(how, what=nil)
      TextField.new(self, how, what)
    end

这下,大家应该明白ie.text_field(how,what)这句话是执行的哪里的函数了!而以上代码中TextField.new是TextField实例化的一个过程,TextField类定义在input_elements.rb中,该类继承自InputElement类,而该类也定义在input_elements.rb中,接下来看下代码:

1)inputElements类的构造函数

    def initialize(container, how, what)
      set_container container
      @how = how
      @what = what
      super(nil)
    end

而TextField类没有定义自己的构造函数,因此直接继承自inputElement的构造函数


到现在为止,已经清晰的描述到了ie.text_field(:class,'kw')处,但到现在还没有真正定位元素,而接下来将介绍.set的过程,该过程将实现元素的实际定位。

set函数:

    def set(value)
      assert_exists
      assert_enabled
      assert_not_readonly
      highlight(:set)
      @o.scrollIntoView
      if type_keys
	      @o.focus
	      @o.select
	      @o.fireEvent("onSelect")
	      @o.fireEvent("onKeyPress")
	      @o.value = ""
	      type_by_character(value)
	      @o.fireEvent("onChange")
	      @o.fireEvent("onBlur")
	    else
				@o.value = limit_to_maxlength(value)
	    end
      highlight(:clear)
    end
在set函数中,assert_exists函数进行了元素定位,即进行了InputElementLocator类的实例化,实例化的具体代码如下,该代码在locator.rb中

    def initialize container, types
      @container = container
      @types = types
      @elements = nil
      @klass = Element
    end
assert_exists函数定义如下,定义在element.rb

    public
    def assert_exists
      #这里出现了定位!
      locate if respond_to?(:locate)
      unless ole_object
        raise UnknownObjectException.new(
                Watir::Exception.message_for_unable_to_locate(@how, @what))
      end
    end
以上代码中的locate定义在input_elements.rb中的InputElement类中

def locate
      @o = @container.locate_input_element(@how, @what, self.class::INPUT_TYPES)
    end

OK,分享完毕!!


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值