为啥要等待?
由于现在的网页大部分使用了AJAX技术,很多网页元素是动态加载的。当我们打开网页时,即使网页的onload方法已经执行完,有些元素还要一些时间才会全部加载出来。
Selenium WebDriver提供两种类型的等待: 隐式等待和显式等待。
- 显式等待是特定条件发生之后,WebDriver再继续执行后面的语句。
- 隐式等待是WebDriver在尝试定位元素前轮询DOM一定的时间。
1、显示等待
WebDriverWait和expected_conditions两个类来实现等待某个事件的发生。
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
wait = WebDriverWait(driver, 10)
element = wait.until(EC.element_to_be_clickable((By.ID, 'XXX')))
Expected Conditions支持的条件:
- title_is
- title_contains
- presence_of_element_located
- visibility_of_element_located
- visibility_of
- presence_of_all_elements_located
- text_to_be_present_in_element
- text_to_be_present_in_element_value
- frame_to_be_available_and_switch_to_it
- invisibility_of_element_located
- element_to_be_clickable
- staleness_of
- element_to_be_selected
- element_located_to_be_selected
- element_selection_state_to_be
- element_located_selection_state_to_be
- alert_is_present
#用法举例:
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
driver = webdriver.Firefox()
driver.get("https://www.bilibili.com/")
try:
element = WebDriverWait(driver, 30).until(
EC.presence_of_element_located((By.ID, "xxx"))
)
finally:
driver.quit()
2、隐式等待
用implicitly_wait函数设置WebDriver在查找元素时最多要轮询多少秒。
#用法举例:
from selenium import webdriver
driver = webdriver.Firefox()
driver.implicitly_wait(10) # seconds
driver.get("http://www.baidu.com")
myDynamicElement = driver.find_element_by_id("xxx")