selenium set waiting notes

Posted by mikebyrne on Sat, 22 Jan 2022 21:48:25 +0100

Set element wait:
webdriver provides two types of element waiting: explicit waiting and implicit waiting

1, Explicit wait
Explicit wait means that the webdriver continues to execute when a condition is satisfied. Otherwise, a timeout exception will be thrown when the maximum time is reached

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

driver = webdriver.Chrome()

driver.get('http://www.baidu.com')

element = WebDriverWait(driver, 5, 0.5).until(
    EC.visibility_of_element_located((By.ID, "kw"))
)

element.send_keys('selenium')
driver.quit()

Problems encountered 1:

EC.visibility_of_element_located(By.ID, "kw")

Then the code reports an error:
TypeError: init() takes 2 positional arguments but 3 were given
Cause of problem:
visibility_ of_ element_ The value passed in the located () method should be a tuple, which is different from the value passed in peacetime, so you need to add an () to make the data type become a tuple
Correct writing:

EC.visibility_of_element_located((By.ID, "kw"))

visibility_ of_ element_ The function of the located () method: judge whether the element is visible (visible means that the element is not hidden, and the height and width of the element are not equal to 0)

WebDriverWait class is a waiting method provided by WebDriver. Within the set time, the default is to detect whether the current page element exists at regular intervals. If it is still not detected after the set time, an exception will be thrown Specific format:

WebDriverWait(driver, timeout, poll_frequency = 0.5, ignored_expections = None)
driver: Browser driven
timeout: Maximum timeout,The default is in seconds
poll_frequency: Interval of detection(step)time,The default is 0.5s
ignored_exceptions: Exception information after timeout,Thrown by default NoSuchEelementException abnormal

WebDriverWait() is generally the same as until() or until_not() method

until(method, message="")

Call the driver provided by the method as a parameter until the return value is True

until_not(method, message="")

Call the driver provided by the method as a parameter until the return value is False
In addition, this example uses the as keyword to convert expected D_ Rename the conditions to EC and call EC visibility_ of_ element_ The loaded () method determines whether the element exists.
expected_ The expected judgment methods provided by the conditionsd class are as follows:

Except expected_ In addition to providing expected condition judgment methods, the conditions class can also use is_ The displayed () method implements the element display wait The code is as follows:

from time import sleep, ctime
from selenium import webdriver
from selenium.webdriver.common.by import By

driver = webdriver.Chrome()
driver.get("http://www.baidu.com")

print(ctime())
for i in range(10):
    try:
        el = driver.find_element(By.id,"kwabc")
        if el.is_displayed():
            break

    except:
        pass

    sleep(1)
else:
    print("time out!")

print(ctime())

driver.quit()

First, for loops 10 times, and then through is_ The displayed () method loops to determine whether the element is visible If True, the element is visible. Execute break to jump out of the loop. Otherwise, execute sleep() to sleep for 1s, and then continue the loop judgment. After 10 cycles, if break is not executed, execute the else statement corresponding to the for loop and print "time out!"
The results are as follows:

Sun Jul  4 17:25:07 2021
time out!
Sun Jul  4 17:25:17 2021

Process finished with exit code 0

2, Implicit waiting
Implicitly provided by webdriver_ The wait () method can be used to implement implicit waiting
For example:

#Implicit waiting
from selenium import webdriver
from time import ctime
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.by import By

driver = webdriver.Chrome()

#Set the implicit wait to 10s
driver.implicitly_wait(10)
driver.get("http://baidu.com")

try:
    print(ctime())
    driver.find_element(By.ID,"kwabc").send_keys("selenium")
	print("Search succeeded")
except NoSuchElementException as e:
    print(e)

finally:
    print(ctime())
    driver.quit()

Result 1:

Sun Jul  4 17:40:14 2021
Message: no such element: Unable to locate element: {"method":"css selector","selector":"[id="kwabc"]"}
  (Session info: chrome=91.0.4472.77)

Sun Jul  4 17:40:24 2021

Process finished with exit code 0

Change "kwabc" to "kw", result 2:

Sun Jul  4 17:42:14 2021
 Search succeeded
Sun Jul  4 17:42:14 2021

Process finished with exit code 0

implicitly_ The parameter of wait() is time, and the unit is s. 10s is not a fixed waiting time and does not affect the speed of script execution Secondly, it will wait for all elements on the page. When the script specifies a positioning element, if the element exists, it will continue to execute (for example, kw will continue to execute when it exists) If the element is not located, it will continuously judge whether the element exists by circular argument Assuming that the element is located at 3s, continue to execute If the element is not located until the 10th s, an exception is thrown (such as result 1)
Reference book: selenium3 automated test practice, based on Python language

Topics: Python Selenium