【appuim】25、显示等待

1、应用场景

  • 针对所有定位元素的超时时间设置为不同的值的时候

2、概念

  • 等待元素加载指定的时长,超出时长抛出TimeoutException异常

3、步骤

  • 导包
  • 创建WebDriverWait对象
  • 调用WebDriverWait对象的until方法

4、方法参数解释

# 参数
# 	driver:驱动对象
#	timeout:超时的市场,单位:秒
#	poll_frequency:检测间隔时间,单位为0.5秒
# 返回值
#	WebDriverWait对象

WebDriverWait(driver, timeout, poll_frequency=0.5)

# 参数
#	method:lambda查找元素表达式
# 返回值
#	定位到的元素,如果没有定位到会抛出TimeoutException异常
wait.until(method)

5、作用

  • 在设置了显式等待之后,可以等待一个超时时间,在这个超时时间之内进行查询,默认每0.5秒找一次
  • 0.5秒的频率是可以设置的
  • 一旦找到这个元素,直接进行后续操作
  • 如果没有找到,报错,TimeOutException

6、示例

  • 在5秒钟内,每1秒在设置程序中的"返回"按钮,如果找到则点击,如果找不到则观察对应的错误信息

7、核心代码

from appium import webdriver
from selenium.webdriver.support.wait import WebDriverWait
import time

desired_caps = dict()
desired_caps['platformName'] = 'Android'
desired_caps['platformVersion'] = '7'
desired_caps['deviceName'] = '192.168.101.55:5555'

# 手机参数
desired_caps['appPackage'] = 'com.android.settings'
desired_caps['appActivity'] = '.Settings'

driver = webdriver.Remote('http://localhost:4723/wd/hub', desired_caps)


print('---开始准备点击了')

# 拆分的写法
# wait = WebDriverWait(driver, 5, 1)
# back_button = wait.until(lambda x: x.find_element_by_xpath('//*[@content-desc="收起"]'))
# back_button.click()

# 简便的写法
WebDriverWait(driver, 5, 1).until(lambda x: x.find_element_by_xpath('//*[@content-desc="收起"]')).click()

# 使用显式等待,在20秒的时间内,每3秒钟找一次,id为xx的元素
WebDriverWait(driver, 20, 3).until(lambda x: x.find_element_by_id('xx'))

print('---点完了')
posted @ 2022-05-31 09:55  郭祺迦  阅读(92)  评论(0)    收藏  举报