from selenium import webdriver
from selenium.webdriver.common.by import By
from time import sleep
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions
driver = webdriver.Chrome()
# 隐式等待: 会等待页面加载完成,最长等待10秒
# driver.implicitly_wait(10)
driver.get("http://www.baidu.com")
driver.find_element(By.ID, "s-top-loginbtn").click()
# 强制等待:
# sleep(3)
# 显示等待:针对某一个/一类元素,每隔0.5秒检查一次,直到这个元素满足条件, 继续往后执行,最长等待30秒时间
wait = WebDriverWait(driver, 30)
# 期望元素存在,但是不一定可见
# (By.ID, "TANGRAM__PSP_11__userName") 通过id查找元素:作为元组传入presence_of_element_located
# wait.until(expected_conditions.presence_of_element_located((By.ID, "TANGRAM__PSP_11__userName")))
# 期望所有元素存在
wait.until(expected_conditions.presence_of_all_elements_located((By.ID, "TANGRAM__PSP_11__userName")))
# 只有有元素可见
# wait.until(expected_conditions.visibility_of_any_elements_located((By.ID, "TANGRAM__PSP_11__userName")))
# 所有元素可见
# wait.until(expected_conditions.visibility_of_all_elements_located((By.ID, "TANGRAM__PSP_11__userName")))
# 单个元素可见
# wait.until(expected_conditions.visibility_of_element_located((By.ID, "TANGRAM__PSP_11__userName")))
driver.find_element(By.ID, "TANGRAM__PSP_11__userName").send_keys("username")
python_selenium 各种等待
于 2022-07-19 10:30:26 首次发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)