In some situations you may need to wait for the new page to load after clicking a link or button. Selenium doesn’t always automatically do that for you, furthermore, sometimes wait.until(presenceOfElement) does not help. Below is a sample page from our company intranet. When we click the button on the left, the page refreshes with the same elements and url, and Selenium does not wait for page refresh before passing to next step i.e, sendingKeys to text box.
So we handled this situation by first waiting for an arbitrary element on the page to pass to “stale” state (element is gone from browser (DOM)) meaning old page has gone disappeared, and then waiting for an arbitrary element on the page to be present again, meaning the new page has been loaded again.
wait.until(ExpectedConditions.stalenessOf(guncelleElement)); wait.until(ExpectedConditions.presenceOfElementLocated(By.cssSelector("input[value='Paketleri Guncelle']")));
Below I give an example using this logic on wikipedia.org because our intranet page is not public. However, in below example Selenium would already automatically wait for the next page to load, but for sake of demonstration of a fully working code I chose wikipedia.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | package com.AUTech.testSynch; import org.junit.Test; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; /** * Created by Ali Ulvi Talipoglu on 18.11.2016. */ public class PageLoadWaitExample { static WebDriver driver; @Test public void testPageLoadSynchronization() throws Exception { System.setProperty("webdriver.gecko.driver", "C:\\geckodriver-v0.11.1-win64\\geckodriver.exe"); driver = new FirefoxDriver(); driver.navigate().to("https://en.wikipedia.org/wiki/Main_Page"); By theLinkToNewPage = By.linkText("Log in"); //Element of the link WebElement theLinkToNewPageElement = driver.findElement(theLinkToNewPage); //Click the link theLinkToNewPageElement.click(); WebDriverWait wait = new WebDriverWait(driver, 60, 100); //wait till the old page disappears wait.until(ExpectedConditions.stalenessOf(theLinkToNewPageElement)); //wait till the new page loads wait.until(ExpectedConditions.presenceOfElementLocated(theLinkToNewPage)); //Page is loaded } } |
You can also use this logic with pages that refresh themselves when an item from a drop-down list is selected.
FACEBOOK COMMENTS WILL BE SHOWN ONLY WHEN YOUR SITE IS ONLINE