1、强制等待
from selenium import webdriver from selenium.webdriver.common.by import By import time driver = webdriver.Chrome() driver.get('https://mail.qq.com/') # 强制等待 time.sleep(5) driver.switch_to.frame('login_frame') # 切换iframe driver.find_element(by=By.XPATH, value="//a[text()='帐号密码登录']").click() driver.quit()
2、隐式等待
from selenium import webdriver from selenium.webdriver.common.by import By driver = webdriver.Chrome() driver.get('https://mail.qq.com/') # 隐式等待:设置查找节点的时候,最大的等待时间 driver.implicitly_wait(30) # 后续执行到定位节点代码时,自动最多等待30s driver.switch_to.frame('login_frame') # 切换iframe driver.find_element(by=By.XPATH, value="//a[text()='帐号密码登录']").click() driver.quit()
3、显式等待
import time from selenium import webdriver from selenium.webdriver.support.wait import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By driver = webdriver.Chrome() driver.get('https://www.baidu.com') # 显式等待: # wait = WebDriverWait(driver, 30, 0.5) # located = (By.XPATH, "//a[text()='新闻']") # conditions = EC.visibility_of_element_located(located) # wait.until(conditions) # 工作中显式等待的写法:(本例表示:最多等30s,每隔0.5s检查一下,直到目标节点符合预期条件--可见) WebDriverWait(driver, 30, 0.5).until( EC.visibility_of_element_located((By.XPATH, "//a[text()='新闻']"))) # 显示等待语句后面可以直接跟操作。如: WebDriverWait(driver, 30, 0.5).until( EC.visibility_of_element_located((By.XPATH, "//a[text()='新闻']"))).click() time.sleep(5) driver.quit()