Summary of waiting methods for Python page loading

  • 2021-09-11 20:52:25
  • OfStack

1. Explicit wait

It specifies the node to be searched, and then specifies 1 longest waiting time. If this node is loaded within the specified time, it returns the searched node; If the node is not loaded within the specified time, a timeout exception is thrown.


from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
broswer = webdriver.Chrome()
broswer.get('https://www.jd.com/')
wait = WebDriverWait(broswer, 20)
input_q = wait.until(EC.presence_of_element_located((By.ID, 'key')))
button = wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, '.button')))
print(input_q, button)

2. Implicit wait

When using implicit wait to execute a test, if Selenium does not find a node in DOM, it will continue to wait, and after the set time, it will throw an exception that no node is found. In other words, when the node is found and the node does not appear, the implicit wait will wait 1 time to find DOM, and the default time is 0. The example is as follows:


from selenium import webdriver
browser = webdriver.Chrome()
browser.implicitly_wait(10)
browser.get('https://www.jd.com/')
input_q = browser.find_element_by_class_name('button')
print(input_q)

Extension of knowledge points:

There are three ways to wait in Python:

1. Forced waiting

Import Timing Waiting Library

from time import sleep or import time

time. sleep (10) # means forcibly waiting for 10s to execute the next sentence of code. This waiting mode will execute the next statement when the time comes, but it is rigid and cannot guarantee that the element is really loaded within the waiting time. Moreover, if the waiting element has been loaded, it is a waste of time to wait until the time before executing the next sentence.

2. Hidden waiting

driver. implicitly_wait (30) # Wait 30s
This wait means that when all the elements of the page are loaded within the specified time, the next step 1 will be executed, otherwise, 1 will wait until the time expires, and then continue to the next step 1.
The disadvantage of this method is that the elements you need have already been loaded, but the page has not been loaded yet, so you need to wait until the page is loaded before performing the next step.

3. Dominant waiting

Packages to be imported


from selenium.webdriver.support.wait import WebDriverWait # Import packages with explicit waiting 

from selenium.webdriver.support import expected_conditions as EC # Determine whether the required elements have been loaded  

from selenium.webdriver.common.by import By # Positioning 

Related articles: