appium的等待

在自动化过程中,元素出现受网络环境,设备性能等多种因素影响。因此元素加载的时间可能不一致,从而会导致元素无法定位超时报错,但是实际上元素是正常加载了的,只是出现时间晚一点而已。那么如何解决这个问题呢?

元素等待作用

设置元素等待可以更加灵活的制定等待定位元素的时间,从而增强脚本的健壮性,提高执行效率。

元素等待类型

强制等待

设置固定的等待时间,使用sleep()方法即可实现

from time import sleep

#强制等待5秒

sleep(5)

隐式等待

隐式等待是针对全部元素设置的等待时间

driver.implicitly_wait(20)

显式等待

显式等待是针对某个元素来设置的等待时间。

方法WebDriverWait格式参数如下:

from selenium.webdriver.support.ui import WebDriverWait

 

WebDriverWait(driver, timeout, poll_frequency=0.5, ignored_exceptions=None)

driver : WebDriver

timeout : 最长超时时间,默认以秒为单位

poll_frequency : 休眠时间的间隔时间,默认为0.5秒

ignored_exceptions : 超时后的异常信息,默认情况下抛NoSuchElementException异常。

WebDriverWait()一般和until()或until_not()方法配合使用,另外,lambda提供了一个运行时动态创建函数的方法。

from selenium.webdriver.support.ui import WebDriverWait

WebDriverWait(driver,10).until(lambda x:x.find_element_by_id("elementID"))

实战案例

测试场景

考研帮登录之后显示等待【论坛】按钮,然后点击。

代码实现

element_wait.py

from find_element.kyb_login import driver

from selenium.webdriver.support.ui import WebDriverWait

 

WebDriverWait(driver,3).until(lambda x:x.find_element_by_id('com.tal.kaoyan:id/mainactivity_button_forum'))

driver.find_element_by_id('com.tal.kaoyan:id/mainactivity_button_forum').click()

猜你喜欢

转载自www.cnblogs.com/xuzhongtao/p/9723192.html