自动化测试——Selenium+Python判断元素是否可见,及元素未出现时设置超时时限
自动化测试中,有时可以根据某元素是否出现(即可见)来进行断言,判断元素是否可见的方法如下:
from selenium.webdriver.support import expected_conditions as EC def is_element_visible(self, element): driver = self.driver try: the_element = EC.visibility_of_element_located(element) assert the_element(driver) flag = True except: flag = False return flag
需要进行判断时,调用此方法即可。
有时在进行操作后,某元素需要一段时间后才能显示,此时可以设置一时间限制,在此时间间隔内不断判断该元素是否可见,若找到则继续后续操作,否则提示元素未找到。代码如下:
from selenium.webdriver.common.by import By from datetime import datetime the_element = is_element_visible(self, (By.ID, "kw")) if the_element: print "element appears." else: time_start = datetime.now() while True:
time_now = datetime.now()
time_difference = (time_now - time_start).seconds
if time_difference < 60: recheck_the_element = is_element_visible(self, (By.ID, "kw"))
if recheck_the_element: print "element appears." break else: continue
else:
print "element not appears."