1

I'm having trouble with my Explicit Wait not always working. They will randomly fail, and I'm not sure why. I'm hitting element not found, or Stale Element. What can I do to make them more reliable?

public class FrameRegisterAccount extends BasicTests
{
// Generates Email
String userName = ""+(int)(Math.random()*Integer.MAX_VALUE);
String emailID = "Otto"+userName+"@gmail.com";

@Test (priority=1)
public void NewAccount() throws Exception {
    WebDriverWait wait = new WebDriverWait(driver, 15, 2500L);
    WebElement signButton = wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//a[@class='button-sign']")));
    signButton.click();
    log.info("New Account Creation Screen Opened");

    // Fill out Form
    WebElement nameField = wait.until(ExpectedConditions.visibilityOfElementLocated(By.name("first_name")));
    nameField.sendKeys("Otto");

    driver.findElement(By.name("last_name")).sendKeys("Mation Tester");
    driver.findElement(By.name("phone_number")).sendKeys("555-555-3231");
    driver.findElement(By.name("listings")).sendKeys("4");

    // Enter Email and Password
    driver.findElement(By.xpath("//input[@name='email']")).clear();
    driver.findElement(By.xpath("//input[@name='email']")).sendKeys(emailID);
    driver.findElement(By.xpath("//input[@name='password']")).clear();
    driver.findElement(By.xpath("//input[@name='password']")).sendKeys("password");

    // Click buttons
    driver.findElement(By.xpath("//div[@class='input input-term']//div[@class='checkbox-icon']")).click();
    driver.findElement(By.xpath("//span[contains(text(),'Sign Up')]")).click();
    Thread.sleep(3000);
    log.info("New Account Created");
}

@Test (priority=2)
public void ChangePassword() {

    // Wait for Dashboard Button
    WebDriverWait wait = new WebDriverWait(driver, 15, 2500L);
    WebElement dashButton = wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//button[contains(@class,'success-dashboard')]")));
    dashButton.click();
    log.info("Go to Dashboard Button Pressed");

    // Change Password
    WebElement proNameX = wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//div[@id='sidebar-top-item']")));
    proNameX.click();
    WebElement changePass = wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//div[@id='nf-change-password-btn']")));
    changePass.click();

    //driver.findElement(By.xpath("//div[@id='nf-change-password-btn']")).click();
    driver.findElement(By.name("old_password")).sendKeys("password");
    driver.findElement(By.name("new_password")).sendKeys("wordpass");
    driver.findElement(By.name("new_password2")).sendKeys("wordpass");
    driver.findElement(By.xpath("//button[@type='button']")).click();
    log.info("Password Change Completed");
}

Stacktrace:

org.openqa.selenium.StaleElementReferenceException: 
stale element reference: element is not attached to the page document
  (Session info: headless chrome=72.0.3626.109)
  (Driver info: chromedriver=2.46.628388 (4a34a70827ac54148e092aafb70504c4ea7ae926),platform=Linux 4.14.88-88.76.amzn2.x86_64 x86_64) (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 0 milliseconds
For documentation on this error, please visit: https://www.seleniumhq.org/exceptions/stale_element_reference.html
Build info: version: '3.141.59', revision: 'e82be7d358', time: '2018-11-14T08:17:03'
System info: host: 'ip-172-31-36-12.us-west-2.compute.internal', ip: '172.31.36.12', os.name: 'Linux', os.arch: 'amd64', os.version: '4.14.88-88.76.amzn2.x86_64', java.version: '1.8.0_131'
Driver info: org.openqa.selenium.chrome.ChromeDriver
Capabilities {acceptInsecureCerts: false, acceptSslCerts: false, applicationCacheEnabled: false, browserConnectionEnabled: false, browserName: chrome, chrome: {chromedriverVersion: 2.46.628388 (4a34a70827ac54..., userDataDir: /tmp/.org.chromium.Chromium...}, cssSelectorsEnabled: true, databaseEnabled: false, goog:chromeOptions: {debuggerAddress: localhost:42199}, handlesAlerts: true, hasTouchScreen: false, javascriptEnabled: true, locationContextEnabled: true, mobileEmulationEnabled: false, nativeEvents: true, networkConnectionEnabled: false, pageLoadStrategy: normal, platform: LINUX, platformName: LINUX, proxy: Proxy(), rotatable: false, setWindowRect: true, strictFileInteractability: false, takesHeapSnapshot: true, takesScreenshot: true, timeouts: {implicit: 0, pageLoad: 300000, script: 30000}, unexpectedAlertBehaviour: ignore, unhandledPromptBehavior: ignore, version: 72.0.3626.109, webStorageEnabled: true}
Session ID: 1a448c188bc68362fa3dc7858ee770b3
    at registerAuto.FrameRegisterAccount.ChangePassword(FrameRegisterAccount.java:57)

Stack 2:

org.openqa.selenium.TimeoutException: Expected condition failed: waiting for element to be clickable: By.xpath: //div[@id='sidebar-top-item'] (tried for 15 second(s) with 2500 milliseconds interval) Build info: version: '3.141.59', revision: 'e82be7d358', time: '2018-11-14T08:17:03' System info: host: 'ip-172-31-36-12.us-west-2.compute.internal', ip: '172.31.36.12', os.name: 'Linux', os.arch: 'amd64', os.version: '4.14.88-88.76.amzn2.x86_64', java.version: '1.8.0_131' Driver info: org.openqa.selenium.chrome.ChromeDriver Capabilities {acceptInsecureCerts: false, acceptSslCerts: false, applicationCacheEnabled: false, browserConnectionEnabled: false, browserName: chrome, chrome: {chromedriverVersion: 2.46.628388 (4a34a70827ac54..., userDataDir: /tmp/.org.chromium.Chromium...}, cssSelectorsEnabled: true, databaseEnabled: false, goog:chromeOptions: {debuggerAddress: localhost:42977}, handlesAlerts: true, hasTouchScreen: false, javascriptEnabled: true, locationContextEnabled: true, mobileEmulationEnabled: false, nativeEvents: true, networkConnectionEnabled: false, pageLoadStrategy: normal, platform: LINUX, platformName: LINUX, proxy: Proxy(), rotatable: false, setWindowRect: true, strictFileInteractability: false, takesHeapSnapshot: true, takesScreenshot: true, timeouts: {implicit: 0, pageLoad: 300000, script: 30000}, unexpectedAlertBehaviour: ignore, unhandledPromptBehavior: ignore, version: 72.0.3626.109, webStorageEnabled: true} Session ID: 7b255ab6a2cf5b58cf3919904e703b2a at allStagingAutomation.FrameRegisterAccountStaging.ChangePassword(FrameRegisterAccountStaging.java:55)

Java Noob
  • 33
  • 4
  • Should I not be using Xpaths when I'm using "WebDriverWait"? – Java Noob Feb 20 '19 at 03:10
  • For which element you are getting staleelementreference exception ? – Sameer Arora Feb 20 '19 at 03:39
  • most of the time its "//button[contains(@class,'success-dashboard')]" this element – Java Noob Feb 20 '19 at 03:47
  • The answer appears to have worked :) Thanks for the help. I do have other Script that hit a "no such element: Unable to locate element:" error. I'll post that code in a momemt – Java Noob Feb 20 '19 at 17:37
  • You are getting nosuchelement which means either your xpath incorrect or you have an iframe, please check if you have an iframe above the element and please accept the answer. Thanks in advance!! – Sameer Arora Feb 20 '19 at 18:06
  • I've checked the Dom and there isn't an iframe above the element. I've tried a bunch of different xpaths with no luck – Java Noob Feb 20 '19 at 18:38
  • As there is no iframe according, Please check the xpath because nosuchelement comes when your xpath is incorrect. – Sameer Arora Feb 20 '19 at 19:30
  • Sorry, looks like "driver.navigate().refresh();" isn't working. Now i hit an "Expected condition failed: waiting for element to be clickable:" at line 57. – Java Noob Feb 20 '19 at 20:03
  • As you have refreshed the page i dont think you need the element to be clickable condition now but still you want that please refer to the link i am providing for the relevant condition for your case: https://stackoverflow.com/questions/14156656/how-to-verify-element-present-or-visible-in-selenium-2-selenium-webdriver – Sameer Arora Feb 20 '19 at 20:07
  • What condition should I use instead? I'm not sure if the link information is relevant for my case – Java Noob Feb 20 '19 at 21:42
  • you can use implicit wait at the class level that would solve your purpose. Refer to the link: https://stackoverflow.com/questions/10941184/equivalent-of-waitforvisible-waitforelementpresent-in-selenium-webdriver-tests-u – Sameer Arora Feb 21 '19 at 03:18
  • I tried implicit wait and had no luck, same issue. – Java Noob Feb 21 '19 at 17:30
  • @SameerArora Could the issue by that I'm finding the element by Xpath? If the "Go to Dashboard" button had a 'Name' or 'ID' would this be a possible fix? Is it better to use 'Name' and/or 'ID' when using waits? – Java Noob Feb 21 '19 at 18:36
  • If your xpath is correct then it doesnt matter but if there is ID then you must try and check if that works – Sameer Arora Feb 21 '19 at 19:54

1 Answers1

0

StaleElementReference exception comes when the element you are trying to interact is no longer in the dom or has become stale. So, you need to refresh the page and then again fetch the element and it would work.

So, please add driver.navigate().refresh(); line of code before the element on which you are getting the exception and then operate on the element and it would work fine.

Sameer Arora
  • 4,439
  • 3
  • 10
  • 20
  • 1
    If the element is stale, you don't need to refresh the page *again*... it's already refreshed. You just need to fetch the element again instead of using the stored variable reference. – JeffC Feb 20 '19 at 06:09
  • @JeffC Not actually, websites can be designed in a different way as well, i can say that because i deal with a website with shows the values from the last loaded results only and when i come back to that page using `driver.navigate().back()` the elements show the StaleElementReference exception even after fetching the elements again, so in that case i had to refresh the page before fetching the elements. – Sameer Arora Feb 20 '19 at 06:13
  • OP is not navigating back. If you fetch the elements after `.back()` they shouldn't be stale. Odds are that your page is slow to load or something is getting refreshed after `.back()` and if you waited, you wouldn't have stale elements. There's no reason for an element to be stale after fetching it unless the page changes *again*. – JeffC Feb 20 '19 at 14:53
  • @JeffC yes i can see that he is not navigating back to the page i was just giving you an example where i had to refresh the page before again fetching the elements and looking at the code of OP, i can see that he is fetching the elements again but still getting the exception and that is why i suggested to refresh the page before fetching the elements again. – Sameer Arora Feb 20 '19 at 15:28