一般情况下,元素的加载会受到网络环境或硬件的影响,所以在做自动化测试的时候需要等待元素加载完成。
三种等待方式可以互相使用。
直接等待
强制等待,线程休眠一定时间,这个是python自带的语法:
import time
time.sleep(3)
这种方法比较被动,因为无法预测在各种条件下需要等待的时间,相反,元素在加载很快的环境下也会强制等待设置好的时间,这样很笨拙。
隐式等待
设置一个等待时间,轮询查找(默认0.5秒)元素是否出现,如果超出设置的时间元素还没出现就抛出异常
隐式等待是全局的设置,适用于所有find_element_*方法
self.driver.implicitly_wait(3)
显式等待
在代码中定义等待条件,当条件发生时才继续执行代码
WebDriverWait配合until()和until_not()方法,根据判断条件进行等待
程序每隔一段时间(默认0.5秒)进行条件判断,如果条件成立,择执行下一步,否则继续等待,直到超过设置的最长时间
实例
import pytest
import time
from time import sleep
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
class TestWait:
def setup(self):
self.driver = webdriver.Chrome("E:\WebDrivers\chromedriver.exe")
self.driver.get("https://ceshiren.com/")
# 隐式等待
# self.driver.implicitly_wait(3)
# def teardown(self):
# self.driver.quit()
def test_wait(self):
self.driver.find_element(By.XPATH, '//*[@title="所有分类"]').click()
# # 直接等待
# time.sleep(3)
# 为显式等待设置条件
def wait(x):
return len(self.driver.find_elements(By.XPATH, '//*[@class="table-heading"]')) > 1
WebDriverWait(self.driver,10).until(wait)
self.driver.find_element(By.XPATH, '//*[@title="有新帖子的话题"]').click()
# print("Hello, I have wait for 3 second~")
if __name__=="__main__":
pytest.main(['test_wait.py','-v'])
显式等待中的条件函数也可用selenium自带的函数来替换,如下
WebDriverWait(self.driver,10).until(expected_conditions.element_to_be_clickable((By.XPATH,'//*[@title="有新帖子的话题"]')))