[selenium]等待

selenium显式等待、隐式等待和期望条件

前言

当网络不稳定或应用页面加载问题时,可以设置等待,以避免网络问题导致找不到元素等异常。

[En]

When the network is unstable or the application page is loaded with a problem, you can set a wait to avoid network problems leading to exceptions such as not finding elements.

隐式等待

隐式等待设置最长等待时间,如果页面在指定时间内加载,则执行下一步,否则等待,直到时间结束。

[En]

Implicit wait sets the maximum wait time, and if the page loads within the specified time, perform the next step, otherwise wait until the time ends.

隐式等待在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="...").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

Original: https://www.cnblogs.com/XY-Heruo/p/16443480.html
Author: 花酒锄作田
Title: [selenium]等待

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/499149/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球