retry.py 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. from time import sleep
  2. from selenium.webdriver.support.ui import WebDriverWait
  3. from selenium.webdriver.support import expected_conditions as EC
  4. from selenium.common.exceptions import TimeoutException
  5. max_retries = 3
  6. timeout = 15
  7. def retry_func(func, retries=max_retries + 1, name=""):
  8. """
  9. Retry the function
  10. """
  11. for i in range(retries):
  12. try:
  13. sleep(1)
  14. return func()
  15. except Exception as e:
  16. if name and i < retries - 1:
  17. print(f"Failed to connect to the {name}. Retrying {i+1}...")
  18. elif i == retries - 1:
  19. raise Exception(
  20. f"Failed to connect to the {name} reached the maximum retries."
  21. )
  22. raise Exception(f"Failed to connect to the {name} reached the maximum retries.")
  23. def locate_element_with_retry(driver, locator, timeout=timeout, retries=max_retries):
  24. """
  25. Locate the element with retry
  26. """
  27. wait = WebDriverWait(driver, timeout)
  28. for _ in range(retries):
  29. try:
  30. return wait.until(EC.presence_of_element_located(locator))
  31. except TimeoutException:
  32. driver.refresh()
  33. return None
  34. def find_clickable_element_with_retry(
  35. driver, locator, timeout=timeout, retries=max_retries
  36. ):
  37. """
  38. Find the clickable element with retry
  39. """
  40. wait = WebDriverWait(driver, timeout)
  41. for _ in range(retries):
  42. try:
  43. return wait.until(EC.element_to_be_clickable(locator))
  44. except TimeoutException:
  45. driver.refresh()
  46. return None