设置等待时间有三种方法:
1.implicitly_wait(self, time_to_wait)
此方法在每个脚本中只设定一次就可以了,其作用为设置一个超时等待时间,如一个语句完成超时时间或者等待一个元素被发现的超时时间,
例如设置为30s,则如果在脚本执行时一个元素无法被找到,会发现在30s后才结束脚本提示失败;
2.WebDriverWait(object)
此方法为一个动态等待,可以在设定的timeout时间内进行等待并搜索,其api参数如下:
WebDriverWait(object):
def __init__(self, driver, timeout, poll_frequency=POLL_FREQUENCY, ignored_exceptions=None):
"""Constructor, takes a WebDriver instance and timeout in seconds.
:Args:
- driver - Instance of WebDriver (Ie, Firefox, Chrome or Remote) 此为一个对象,如设定的driver=webdriver.Firefox()
- timeout - Number of seconds before timing out 超时时间
- poll_frequency - sleep interval between calls 默认的在超时时间内两次等待的时间,默认为0.5s
By default, it is 0.5 second.
- ignored_exceptions - iterable structure of exception classes ignored during calls. 在等待时间内需要忽略的异常(此不常用)
用法:
由于在html中有的div是在某个动作如点击完成后才会显示,如一些窗口,下拉列表等通常为disable:none状态.
那么使用此方法可以动态等待窗口或者下拉列表变为disable状态,以进行下一步动作.
此函数通常和until或者until_not函数一起用,以until为例:
WebDriverWait(driver,3).until(lambda driver:driver.find_element_by_xpath(project_dir['xpath_edit_panel']).is_displayed(), "panel open fail")
或者也可以使用如下方式:
dri=driver.find_element_by_xpath(project_dir['xpath_edit_panel']).is_displayed()
WebDriverWait(driver,3).until(dri, "panel open fail")
另附上until()语法,此函数有两个参数,第一个为一个表达式,其值或者返回值应当为true或者false,第二个参数为一个字符串,可不写
3.time.sleep(seconds)
此方法需先导入time模块,会根据设定固定等待一段时间,较为常用,如等待页面生成某个元素等,
使用较为简单,如time.sleep(3)即为等待3s钟.