retry.py 1.7 KB

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