Three Methods for Setting Element Waiting in Python Selenium

Why do we need to set element waiting

1. Sleep forced waiting
The code is as follows.

from selenium import webdriver
from time import sleep
dr = webdriver.Chrome()
sleep(2)        #set to wait for 2 seconds 
dr.get('http://www.baidu.com')

Advantages: The code is concise and not verbose

2. Implicitly_Wait() implicit waiting
The code is as follows:

from selenium import webdriver
from time import sleep
dr = webdriver.Chrome()
dr.implicitly_wait(20)  #set to wait for 20 seconds 
dr.get('http://www.baidu.com')
dr.find_element_by_id('kw').send_keys('shawn')
dr.find_element_by_id('su').click()

Advantages:
1. The code is concise.
2. Implicitly add to the front of the code_Wait() will be effective throughout the entire program execution process, waiting for the elements to load and not needing to be set every time like sleep<3. If the entire page is not loaded within the set time, NosuchElementError will be reported. If the element is loaded in the 20th second, the following script will be automatically executed and will not wait for 20 seconds.

Disadvantage: It is necessary to load the entire page before executing the code, which affects the efficiency of code execution. Generally, the desired result is to only load the element I want to locate and execute the code, without waiting for the entire page to be fully loaded before executing the code.

3. WebDriverWait() displays wait .

from selenium import webdriver
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait       #WebDriverWait pay attention to capitalization 
from selenium.webdriver.common.by import By
dr = webdriver.Chrome()
dr.get('http://www.baidu.com')
try:
element = WebDriverWait(dr,10).until(EC.presence_of_element_located((By.ID,'kw')))
element.send_keys('123')
dr.find_element_by_id('su').click()
except Exception as message:
print('element positioning error %s'%message)
finally:
pass

Advantages: Fast code execution efficiency. No need to wait for the entire page to load, just load it onto the element you want to locate to execute the code. It is the most intelligent way to set element waiting.

Disadvantages:
1. To import from selenium. webdriver. support import expected_Conditions as EC
from selenium. webdriver. support. ui import WebDriverWait
from selenium. webdriver. common. by import By
It is necessary to import the above three packages, and the export path is quite complex, verbose, and troublesome
2. Writing code for the wait time is also complex. The steps are a bit too many.
element= WebDriverWait (dr, 10). until (EC. presentationof elementrelocated (By. ID, 'kw'))
element. send_Keys ('123 ').

Related articles