selenium的三种等待方式
selenium中一般分为三种等待方式:显示等待、隐式等待、sleep强制等待
1、显示等待(有条件)
程序提前指定等待条件和等待时间,在查找元素时,判断规定时间内是否满足条件,满足则继续执行,不满足或超出时间则抛出异常
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait #导入显示等待模块from selenium.webdriver.support import expected_conditions as EC #导入显示等待条件import time
driver = webdriver.Chrome()'''显示等待'''
driver.get('https://www.baidu.com')'driver 是 webdriver对象,最长等待5s,每0.5秒查询对应的元素,until判断是否满足等待条件'print(time.time())
baidu_submit = WebDriverWait(driver,5,0.5).until(EC.presence_of_element_located((By.ID,'su')))print(time.time())# 即将执行的js语句
js ='alert("检测百度一下按钮成功")'if baidu_submit:
driver.execute_script(js)
2、隐式等待(无条件)
程序提前指定等待时间,在查找元素时,首先会在DOM中查找元素,如果找不到,就继续等待,在等待时间结束之后,再一次查找,如果找到元素则继续执行,没有找到则抛出异常
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait #导入显示等待模块from selenium.webdriver.support import expected_conditions as EC #导入显示等待条件import time
driver = webdriver.Chrome()'''隐式等待'''
driver.implicitly_wait(5)
driver.get('https://www.baidu.com')print(time.time())
baidu_submit = driver.find_element(*(By.ID,'su'))print(time.time())# 即将执行的js语句
js ='alert("检测百度一下按钮成功")'if baidu_submit:
driver.execute_script(js)
3、sleep强制等待
使用time库中的sleep()方法使程序睡眠,强制等待一段时间后继续执行
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait #导入显示等待模块from selenium.webdriver.support import expected_conditions as EC #导入显示等待条件import time
driver = webdriver.Chrome()'''强制等待'''
driver.get('https://www.baidu.com')print(time.time())
baidu_submit = driver.find_element(*(By.ID,'su'))
time.sleep(5)print(time.time())
js ='alert("检测百度一下按钮成功")'if baidu_submit:
driver.execute_script(js)
版权归原作者 blog-xiaoh 所有, 如有侵权,请联系我们删除。