catalogue
Waiting time is a key point when we do automated testing. Many page jumps and loads take time. If we do not set the waiting time and the elements are not loaded, the program will report an error, and a stable automated testing code will certainly have test waiting time.
A sleep of Python time module
from selenium import webdriver from time import sleep driver = webdriver.Firefox() #Create Firefox object driver.get( "https://www.baidu.com/") #Open baidu sleep( 5) #Wait 5 ms driver.quit() #Close browser
Generally, it is not recommended because this is a mandatory wait. If you set 10S, it will always wait for 10S. If you have a lot of scripts, the execution time and efficiency will be very slow. How to improve the execution efficiency, I think one thing is to use less sleep.
Second, implicit waiting
Let's look at the source code first:
Set the sticky timeout to implicitly wait for the element to be found, or to complete the command. This method only needs to call one time per meeting. Set the timeout for the call execute_async_script, see set_script_timeout.
: number of parameters:
- time_to_wait: wait time (in seconds)
from selenium import webdriver driver = webdriver.Chrome() driver.implicitly_wait( 10) #Here, set the intelligent wait for 10s driver.get( 'https://www.baidu.com') print (driver.title) driver.quit()
Summary: set the maximum waiting time of 10S. If no element is found within 10S, a NoSuchElementException exception will be thrown. If an element is not found, wait for a period of time until an element position is obtained
Note: when using implicit waiting, the browser will refresh the page to find the elements we need within the time you set, which will not affect the execution speed of our script.
III. display waiting
Look at the source code:
# Licensed to the Software Freedom Conservancy (SFC) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The SFC licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. import time from selenium.common.exceptions import NoSuchElementException from selenium.common.exceptions import TimeoutException POLL_FREQUENCY = 0.5 # How long to sleep inbetween calls to the method IGNORED_EXCEPTIONS = (NoSuchElementException,) # exceptions ignored during calls to the method class WebDriverWait(object): def __init__(self, driver, timeout, poll_frequency=POLL_FREQUENCY, ignored_exceptions=None): """Constructor, takes a WebDriver instance and timeout in seconds. :Args: - driver - Instance of WebDriver (Ie, Firefox, Chrome or Remote) - timeout - Number of seconds before timing out - poll_frequency - sleep interval between calls By default, it is 0.5 second. - ignored_exceptions - iterable structure of exception classes ignored during calls. By default, it contains NoSuchElementException only. Example: from selenium.webdriver.support.ui import WebDriverWait \n element = WebDriverWait(driver, 10).until(lambda x: x.find_element_by_id("someId")) \n is_disappeared = WebDriverWait(driver, 30, 1, (ElementNotVisibleException)).\ \n until_not(lambda x: x.find_element_by_id("someId").is_displayed()) """ self._driver = driver self._timeout = timeout self._poll = poll_frequency # avoid the divide by zero if self._poll == 0: self._poll = POLL_FREQUENCY exceptions = list(IGNORED_EXCEPTIONS) if ignored_exceptions is not None: try: exceptions.extend(iter(ignored_exceptions)) except TypeError: # ignored_exceptions is not iterable exceptions.append(ignored_exceptions) self._ignored_exceptions = tuple(exceptions) def __repr__(self): return '<{0.__module__}.{0.__name__} (session="{1}")>'.format( type(self), self._driver.session_id) def until(self, method, message=''): """Calls the method provided with the driver as an argument until the \ return value is not False.""" screen = None stacktrace = None end_time = time.time() + self._timeout while True: try: value = method(self._driver) if value: return value except self._ignored_exceptions as exc: screen = getattr(exc, 'screen', None) stacktrace = getattr(exc, 'stacktrace', None) time.sleep(self._poll) if time.time() > end_time: break raise TimeoutException(message, screen, stacktrace) def until_not(self, method, message=''): """Calls the method provided with the driver as an argument until the \ return value is False.""" end_time = time.time() + self._timeout while True: try: value = method(self._driver) if not value: return value except self._ignored_exceptions: return True time.sleep(self._poll) if time.time() > end_time: break raise TimeoutException(message)
Constructor to get the WebDriver instance and time out within a few seconds.
: number of parameters:
- driver - an instance of WebDriver (i.e., Firefox, Chrome or remote)
- timeout - the number of seconds before the timeout
- poll_frequency - sleep interval between calls (monitored interval)
By default, it is 0.5 seconds.
- ignored_exceptions - error messages after timeout.
By default, it contains only NoSuchElementException.
Two examples in the source code: wait for 10S until someID appears, using Python's anonymous function.
element = WebDriverWait(driver, 10).until(lambda x: x.find_element_by_id( "someId")) is_disappeared = WebDriverWait(driver, 30, 1, (ElementNotVisibleException)).\ until_not(lambda x: x.find_element_by_id( "someId").is_displayed())
example:
Import package:
from selenium.webdriver.support.ui import WebDriverWait
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.FireFox() driver.get( 'http://www.baidu') element = WebDriverWait(driver, 5, 0.5).util( EC.presence_of_element_located((By.ID, 'kw')) ) element.send_keys( 'hello') driver.quit()
Handle the waiting time flexibly according to the judgment conditions. He will continue to judge according to the conditions you set until it exceeds the waiting time you set. If the set conditions are met, then proceed to the next step. If they are not met, an error will be reported.
Summary: do not operate until the element appears or the conditions we set are met. If the timeout occurs, an exception will be reported
IV. summary:
- Implicit waiting will wait for the driver to complete loading within the set time;
- The display wait only verifies whether the element to be loaded exists or meets the conditions set by us;
- Forced waiting, no matter what, be sure to wait for the time you set.