Python+Selenium automated testing waiting time

catalogue

A sleep of Python time module

Second, implicit waiting

III. display waiting

IV. summary:

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

   
  1. from selenium import webdriver
  2. from time import sleep
  3. driver = webdriver.Firefox() #Create Firefox object
  4. driver.get( "https://www.baidu.com/") #Open baidu
  5. sleep( 5) #Wait 5 ms
  6. 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)

 

   
  1. from selenium import webdriver
  2. driver = webdriver.Chrome()
  3. driver.implicitly_wait( 10) #Here, set the intelligent wait for 10s
  4. driver.get( 'https://www.baidu.com')
  5. print (driver.title)
  6. 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:

   
  1. # Licensed to the Software Freedom Conservancy (SFC) under one
  2. # or more contributor license agreements. See the NOTICE file
  3. # distributed with this work for additional information
  4. # regarding copyright ownership. The SFC licenses this file
  5. # to you under the Apache License, Version 2.0 (the
  6. # "License"); you may not use this file except in compliance
  7. # with the License. You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing,
  12. # software distributed under the License is distributed on an
  13. # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  14. # KIND, either express or implied. See the License for the
  15. # specific language governing permissions and limitations
  16. # under the License.
  17. import time
  18. from selenium.common.exceptions import NoSuchElementException
  19. from selenium.common.exceptions import TimeoutException
  20. POLL_FREQUENCY = 0.5 # How long to sleep inbetween calls to the method
  21. IGNORED_EXCEPTIONS = (NoSuchElementException,) # exceptions ignored during calls to the method
  22. class WebDriverWait(object):
  23. def __init__(self, driver, timeout, poll_frequency=POLL_FREQUENCY, ignored_exceptions=None):
  24. """Constructor, takes a WebDriver instance and timeout in seconds.
  25. :Args:
  26. - driver - Instance of WebDriver (Ie, Firefox, Chrome or Remote)
  27. - timeout - Number of seconds before timing out
  28. - poll_frequency - sleep interval between calls
  29. By default, it is 0.5 second.
  30. - ignored_exceptions - iterable structure of exception classes ignored during calls.
  31. By default, it contains NoSuchElementException only.
  32. Example:
  33. from selenium.webdriver.support.ui import WebDriverWait \n
  34. element = WebDriverWait(driver, 10).until(lambda x: x.find_element_by_id("someId")) \n
  35. is_disappeared = WebDriverWait(driver, 30, 1, (ElementNotVisibleException)).\ \n
  36. until_not(lambda x: x.find_element_by_id("someId").is_displayed())
  37. """
  38. self._driver = driver
  39. self._timeout = timeout
  40. self._poll = poll_frequency
  41. # avoid the divide by zero
  42. if self._poll == 0:
  43. self._poll = POLL_FREQUENCY
  44. exceptions = list(IGNORED_EXCEPTIONS)
  45. if ignored_exceptions is not None:
  46. try:
  47. exceptions.extend(iter(ignored_exceptions))
  48. except TypeError: # ignored_exceptions is not iterable
  49. exceptions.append(ignored_exceptions)
  50. self._ignored_exceptions = tuple(exceptions)
  51. def __repr__(self):
  52. return '<{0.__module__}.{0.__name__} (session="{1}")>'.format(
  53. type(self), self._driver.session_id)
  54. def until(self, method, message=''):
  55. """Calls the method provided with the driver as an argument until the \
  56. return value is not False."""
  57. screen = None
  58. stacktrace = None
  59. end_time = time.time() + self._timeout
  60. while True:
  61. try:
  62. value = method(self._driver)
  63. if value:
  64. return value
  65. except self._ignored_exceptions as exc:
  66. screen = getattr(exc, 'screen', None)
  67. stacktrace = getattr(exc, 'stacktrace', None)
  68. time.sleep(self._poll)
  69. if time.time() > end_time:
  70. break
  71. raise TimeoutException(message, screen, stacktrace)
  72. def until_not(self, method, message=''):
  73. """Calls the method provided with the driver as an argument until the \
  74. return value is False."""
  75. end_time = time.time() + self._timeout
  76. while True:
  77. try:
  78. value = method(self._driver)
  79. if not value:
  80. return value
  81. except self._ignored_exceptions:
  82. return True
  83. time.sleep(self._poll)
  84. if time.time() > end_time:
  85. break
  86. 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.

   
  1. element = WebDriverWait(driver, 10).until(lambda x: x.find_element_by_id( "someId"))
  2. is_disappeared = WebDriverWait(driver, 30, 1, (ElementNotVisibleException)).\
  3. until_not(lambda x: x.find_element_by_id( "someId").is_displayed())

example:

Import package:

from selenium.webdriver.support.ui import WebDriverWait
   

 

   
  1. from selenium import webdriver
  2. from selenium.webdriver.common. by import By
  3. from selenium.webdriver.support.ui import WebDriverWait
  4. from selenium.webdriver.support import expected_conditions as EC
  5. driver = webdriver.FireFox()
  6. driver.get( 'http://www.baidu')
  7. element = WebDriverWait(driver, 5, 0.5).util(
  8. EC.presence_of_element_located((By.ID, 'kw'))
  9. )
  10. element.send_keys( 'hello')
  11. 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:

  1. Implicit waiting will wait for the driver to complete loading within the set time;
  2. The display wait only verifies whether the element to be loaded exists or meets the conditions set by us;
  3. Forced waiting, no matter what, be sure to wait for the time you set.

 

Keywords: Python

Added by cyanblue on Wed, 22 Dec 2021 07:43:04 +0200