5-selenium set element wait


When loading the page, you will encounter the code execution, but the element is not loaded, it will report an error that the element
can not be found. At this point, you can set the element to wait to solve this problem.

Webdriver provides two kinds of element waiting: display waiting and implicit waiting

One, display waiting

Principle: continue execution when waiting, terminate and throw an exception when not waiting

Disadvantages: cumbersome, many steps

Need to introduce these libraries:

# 设置元素定位使用哪种方法
from selenium.webdriver.common.by import By 
# 元素等待类
from selenium.webdriver.support.ui import WebDriverWait 
# 提供条件判断函数
from selenium.webdriver.support import expected_conditions as EC 

Instructions:

# 代码解释:
# webdriver会等到EC.visibility_of_element_located这个条件成立,
# 每隔0.5s检查一次,最多等待5s。条件成立时就继续执行,否则抛出异常
browser = webdriver.Chrome()
browser.get('网址')

element = WebDriverWait(browser,5,0.5).until(
    EC.visibility_of_element_located(
        (By.CSS_SELECTOR,css元素定位表达式)
    )
)

Two, implicit wait

Similar to display waiting, it will continue to execute within the maximum waiting time range, and report an error if it does not wait.

browser = webdriver.Chrome()
browser.get('网址')

# 申明隐式等待,只对申明之后的代码有效,默认单位:秒,默认轮询时间0.5s
browser.implicitly_wait(5) 

3. Comparison of display waiting, implicit waiting, and forced waiting

1. Display waiting saves time than implicit waiting

2. Implicit wait is simpler than explicit wait

3. Forced waiting will reduce the efficiency of code execution, even if the element is loaded, it will still wait

how to choose?

If the performance of the local computer is not very good and the loading is slow, you can use forced wait;
if the amount of code is small, you can use implicit wait;
if the amount of code is large, it is recommended to use display wait, and encapsulate the display wait as a method to call

Guess you like

Origin blog.csdn.net/weixin_45128456/article/details/113871031