强制等待
sleep(sec)
- 不推荐,但调试或不得不使用时强制等待时可使用
隐式等待
driver.implicitly_wait(sec)
- 隐式等待时长设置为3-6s,不宜太长
显示等待
WebDriverWait(self.driver,10).until(expected_conditions.visibility_of_element_located(locator))
- 一般页面元素的呈现
1.首先,title
2.其次,dom(隐式等待判断元素是否已出现在dom树里,但无法判断其属性是否展示)
3.然后,css(可见visibility)
4.最后,js(可点击clickable,显示等待一般判断元素是否可见、可点击) - html是自上而下加载的
- js加载会阻塞html的加载,为此有些js使用异步加载的方式
- 显示等待设置时长可长一些,比如上传文件需要20s,显示等待时间就可设置为20s
expected_condition
presence_of_element_located
只能判断此元素在dom里,不能判断元素的属性(如可点击、可见的等)已添加
案例
from time import sleep
from appium import webdriver
from appium.webdriver.common.mobileby import MobileBy
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.support.wait import WebDriverWait
class TestDW:
def setup(self):
desired_caps = {
"platformName": "Android",
"deviceName": "127.0.0.1:7555",
"platformVersion": "6.0",
"appPackage": "com.xueqiu.android",
"appActivity": ".view.WelcomeActivityAlias",
"noReset": "true",
"skipDeviceInitialization": "true",
"unicodeKeyBoard": "true",
"resetKeyBoard": "true"
}
self.driver = webdriver.Remote('http://127.0.0.1:4723/wd/hub', desired_caps)
self.driver.implicitly_wait(10)
def teardown(self):
self.driver.back()
def test_search(self):
self.driver.find_element_by_id("com.xueqiu.android:id/tv_search").click()
self.driver.find_element_by_id("com.xueqiu.android:id/search_input_text").send_keys("alibaba")
self.driver.find_element_by_xpath("//*[@resource-id='com.xueqiu.android:id/name' and @text='阿里巴巴']").click()
locator = (MobileBy.XPATH, "//*[@text='09988']/../../..//*[@resource-id='com.xueqiu.android:id/current_price']")
ele = WebDriverWait(self.driver, 10).until(lambda x: x.find_element(*locator))
print(ele.text)
current_price = float(ele.text)
expect_price = 170
assert current_price > expect_price
sleep(3)