Jd Francis Jd Francis - 4 months ago 14
Python Question

Check when page has switched to another page using Selenium in Python

I'm currently using Selenium in Python and I'm running into the issue of tracking when a page has switched to another page.
So say I have the following code to open up a page and then login:

self.driver.get(targeturl)
login = self.driver.find_element_by_name("login")
login.send_keys("user1")
password = self.driver.find_element_by_name("password")
password.send_keys("password123")
login.submit()
#How do I find when the page has changed after submit()?


After the login form is submitted, the page switches to another page. How can I use Selenium to determine exactly when the first page has switched to the second page?

Answer

The best solution I found was a combination of suggestions. The solution is to check for the presence of a new <body> tag based on Bryan Oakley's comment and check for elements, like in Yu's responses (I used <body> instead of <html> because <html> didnt catch page changes inside a dynamic framework where the body is the only thing that changes). I found that doing this worked best for all the pages and had the most versatility (as in I don't need to know any specific ids/details on the page, just that the page has changed). The final solution ended up being this:

self.driver.get(targeturl)
#To check when the first page is loaded, a first wait goes here
WebDriverWait(self.driver,10).until(EC.presence_of_element_located((By.TAG_NAME, 'body'))) 
login = self.driver.find_element_by_name("login")
login.send_keys("user1")
password = self.driver.find_element_by_name("password")
password.send_keys("password123")
login.submit()
#To check when the second page has finished loaded, another wait goes here
WebDriverWait(self.driver, 10).until(EC.presence_of_element_located((By.TAG_NAME, 'body')))

This works for any and all page changes/refreshes. It checks for when a page has finished loading.

Comments