How to wait for a specific URL to load before calling a function using Selenium and Python How to wait for a specific URL to load before calling a function using Selenium and Python selenium selenium

How to wait for a specific URL to load before calling a function using Selenium and Python


If your usecase is to run a function once the url is equal to https://www.example.com you induce WebDriverWait inconjunction with either of the following expected_conditions:

  • url_changes(url): An expectation for checking the current url which must not be an exact match.

    WebDriverWait(driver, 30).until(EC.url_changes("https://www.example.com"))
  • url_contains(url): An expectation for the URL of the current page to contain specific text.

    WebDriverWait(driver, 30).until(EC.url_contains("example"))
  • url_matches(pattern): An expectation for the URL to match a specific regular expression.

    WebDriverWait(driver, 30).until(EC.url_matches("a_matching_pattern_of_the_expected_url"))
  • url_to_be(url): An expectation for the URL of the current page to be a specific url.

    WebDriverWait(driver, 30).until(EC.url_to_be("https://www.example.com"))
  • Note : You have to add the following imports :

    from selenium.webdriver.support.ui import WebDriverWaitfrom selenium.webdriver.support import expected_conditions as EC

However, WebDriverWait in conjunction with the above mentioned expected_conditions may not guarantee that all the elements within the DOM Tree are completely loaded.

You can find a detailed discussion in Do we have any generic function to check if page has completely loaded in Selenium


Update

To run a function if the WebDriverWait returns True you can use the following solution:

try:    WebDriverWait(driver, 30).until(EC.url_to_be("https://www.example.com")))    print("Desired url was rendered with in allocated time")    # now you can call the method/function    # test_me("Holger")except TimeoutException:    print("Desired url was not rendered with in allocated time")

Note : You have to add the following imports :

from selenium.webdriver.support.ui import WebDriverWaitfrom selenium.webdriver.support import expected_conditions as ECfrom selenium.common.exceptions import TimeoutException

Reference

You can find a relevant detailed discussion in: