前言
當網路不穩定或應用頁面加載有問題,可以設定等待,避免網路問題導致找不到元素等例外,
隱式等待
隱式等待設定的是最長等待時間,如果在規定時間內網頁加載完成,則執行下一步,否則一直等到時間結束,
隱式等待在driver的整個生命周期都有效,初始化的時候設定一次即可,
# 隱式等待10秒
driver.implicitly_wait(10)
顯式等待
from selenium.webdriver.support.ui import WebDriverWait
# 使用js的方式等待頁面加載
# 最長顯式等待10秒
WebDriverWait(driver, 10).until(lambda driver: driver.execute_script('return document.readyState') == 'complete')
print("頁面加載完成")
driver.find_element(by=By.CSS_SELECTOR, value="https://www.cnblogs.com/XY-Heruo/p/...").click()
# 使用期望條件
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
WebDriverWait(driver,timeout).until(EC.presence_of_element_located((By.ID, "query")))
EC期望條件
| 條件 | 說明 |
|---|---|
| title_is | title是否已出現 |
| title_contains | title中是否包含某些字符 |
| presence_of_element_located | 元素是否已被加載到dom樹,并不代表元素一定可見 |
| visibility_of_element_lcoated | 元素是否已被加載到dom樹且可見 |
| visibility_of | 元素是否可見 |
| presence_of_all_elements_located | 是否有至少一個元素存在于dom樹 |
| visibility_of_any_elements_located | 是否至少有一個元素可見 |
| text_to_be_present_in_element | 元素是否包含預期字符 |
| text_to_be_present_in_element_value | 元素的屬性值是否包含預期字符 |
| frame_to_be_available_and_switch_to_it | frame是否可切換進去 |
| invisibility_of_element_located | 元素是否存在于dom或不可見 |
| element_to_be_clickable | 元素是否可見且可點擊 |
| staleness_of | 等待元素從dom中移除 |
| element_selection_state_to_be | 元素選中狀態是否符合預期 |
| element_located_selection_state_to_be | 元素選中狀態是否符合預期 |
| alert_is_present | 頁面似乎存在alert |
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/498495.html
標籤:Python
