Selenium2Library源码解析与扩展(二)

说明:下面说到的一些扩展也适用于AppiumLibrary。

_waiting.py

包括一些等待操作,常用来等待页面加载完成,如:

Input Text    css=.username    admin
Input Text    css=.password    123456
Wait Until Page Contains Element   css=.loginsuccess
#Now [sleep] is not need 
Click Element    link=xxxx

使用如上方法,即可不用使用sleep等待登录后页面加载,并能在第一时间点击’link=xxxx’元素。
wait_until_page_contains_element()实现如下:

def wait_until_page_contains_element(self, locator, timeout=None, error=None):
    """Waits until element specified with `locator` appears on current page.

    Fails if `timeout` expires before the element appears. 
    """
    if not error:
        error = "Element '%s' did not appear in <TIMEOUT>" % locator
    #这里通过_is_element_present()在设置超时范围内一直判断locator匹配元素出现
    self._wait_until(timeout, error, self._is_element_present, locator)

_wait_until()实现如下:

def _wait_until(self, timeout, error, function, *args):
    error = error.replace('<TIMEOUT>', self._format_timeout(timeout))
    def wait_func():
        return None if function(*args) else error
    #不断执行function(*args)直到wait_func()返回None
    self._wait_until_no_error(timeout, wait_func)

然后就是_waiting.py的核心_wait_until_no_error()了,实现如下:

def _wait_until_no_error(self, timeout, wait_func, *args):
    #格式化输入的超时时间(从而支持'3s'、'1min'),如果为None,则读取默认配置
    timeout = robot.utils.timestr_to_secs(timeout) if timeout is not None else self._timeout_in_secs
    maxtime = time.time() + timeout
    #死循环
    while True:
        timeout_error = wait_func(*args)
        if not timeout_error: return
        #超时,抛出之前设置的error
        if time.time() > maxtime:
            raise AssertionError(timeout_error)
        time.sleep(0.2)

受此启发,在平常编写脚本一般会在每步操作加若干sleep延时,以增加脚本稳定性:

Click Element    link=lk
Sleep    5s
Input Text    css=.input    hello dassh
Sleep    5s
Click Element    css=.btn

当脚本长到一定程度时,使用sleep消耗的时间就非常可观了,扩展方法如下:

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值