I am using Python3 and Selenium firefox to submit a form and then get the URL that they then land on. I am doing it like this
inputElement.send_keys(postnumber)
inputElement.submit()
time.sleep(5)
# Get Current URL
current_url = driver.current_url
print ( " URL : %s" % current_url )
This is working most of the time but sometimes the page takes longer than 5 seconds to load and I get the old URL as the new one hasn't loaded yet.
How should I be doing this?
url_changes helper from expected_conditions is exactly for this purpose:
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
# some work on current page, code omitted
# save current page url
current_url = driver.current_url
# initiate page transition, e.g.:
input_element.send_keys(post_number)
input_element.submit()
# wait for URL to change with 15 seconds timeout
WebDriverWait(driver, 15).until(EC.url_changes(current_url))
# print new URL
new_url = driver.current_url
print(new_url)
In my code I have created a context manager that does the following:
html element goes stale (which means the page has started to reload)document.readyState to be "complete" (which means the page has finished initial loading)If the page has content that is populated with additional ajax calls, I may add another wait after that for an element that I know doesn't appear immediately after the above four steps.
For a thorough description, see this blog post: How to get Selenium to wait for page load after a click
Try following approach:
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait as wait
from selenium.webdriver.support import expected_conditions as EC
title = driver.title
inputElement.send_keys(postnumber)
inputElement.submit()
wait(driver, 15).until_not(EC.title_is(title))
current_url = driver.current_url
print ( " URL : %s" % current_url )
This will allow you to wait up to 15 seconds until page title is changed (in case there are different titles on new and old pages) after form submission to get new URL. If you want to handle element on new page, then you might need to use below code:
inputElement.send_keys(postnumber)
inputElement.submit()
text_of_element_on_new_page = wait(driver, 15).until(EC.presence_of_element_located((By.ID, "some_element_id"))).text
print ( " Text of element is : %s" % text_of_element_on_new_page )