说明:下面说到的一些扩展也适用于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消耗的时间就非常可观了,扩展方法如下: