概念:
显示等待是针对某一个元素进行相关等待判定;
隐式等待不针对某一个元素进行等待,全局元素等待。
相关模块:
WebDriverWait 显示等待针对元素必用
expected conditions 预期条件类(里面包含方法可以调用,用于显示等待)
NoSuchElementException 用于隐式等待抛出异常
By 用于元素定位
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
from selenium.common.exceptions import NoSuchElementException
示例:
-- 显示等待
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
from time import sleep
driver = webdriver.Chrome()
driver.get("https://www.baidu.com")
driver.maximize_window()
sleep(2)
driver.find_element_by_css_selector("#kw").send_keys("test1")
sleep(2)
# 显示等待 --检测搜索按钮是否存在
# (driver,5,1) 最长等待5秒,每隔0.5秒检测一次
# presence_of_element_located 显示定位元素
element = WebDriverWait(driver,5,0.5).until(EC.presence_of_element_located((By.ID,"su")))
element.click()
sleep(2)
driver.quit()
-- 隐式等待
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
# ctime 获取当前时间
from time import sleep,ctime
driver = webdriver.Chrome()
driver.get("https://www.baidu.com")
driver.maximize_window()
sleep(2)
# 等待5秒
driver.implicitly_wait(5)
try:
print(ctime())
driver.find_element_by_css_selector("#kw").send_keys("test1")
driver.find_element_by_css_selector("#su").click()
except NoSuchElementException as msg:
print(msg)
finally:
print(ctime())
sleep(2)
driver.quit()