0

(A disclaimer to start, I'm still learning Selenium so if there's any horrifically bad practices going on here please let me know)

I am attempting to use Selenium to input some text into a field, waiting for the resulting page to load, and then grabbing a specific DOM element. My input texts are in an array

@Test
public void test() throws Exception {
    final String[] terms = new String[] {"foo", "baz", "bar"};
    for (String term: terms) {
      search(term);
    }
}

private void search(String searchTerm) { 
    driver.get(myPage);
    driver.findElement(By.xpath(xpath)).sendKeys(searchTerm);
    // Press enter
    System.out.println(driver.findElement(By.className("theThingIWant").getText());
    System.out.println(driver.findElement(By.className("anotherThingIWant").getText());
}

Obviously, this isn't all the code, but for the sake of keeping the post short I wanted to provide the jist of what I'm trying to do. When I run this, I occasionally get a StaleElementReferenceException from one of the print statements. This behavior is non deterministic: sometimes it shows up, other times it doesn't show up and the test runs successfully, and when it does show up, it doesn't show up at the same point. For ex, sometimes it'll show up when searching baz, other times it shows up when searching bar, sometimes it'll show up in the first print statement and sometimes at the second.

I'm taking a hunch that the for loop is going too fast, causing the driver to go back to myPage and search for the next term as my code is still attempting to acccess theThingIWant or anotherThingIWant. If I'm wrong, please let me know, but I'd greatly appreciate some insight on attempting to solve this problem

Edit: A note, the code works perfectly fine when I only run one search element without the for loop, eg. search("foo") or search("baz") will run just fine

erli
  • 358
  • 4
  • 16
  • Does this answer your question? [How to avoid "StaleElementReferenceException" in Selenium?](https://stackoverflow.com/questions/12967541/how-to-avoid-staleelementreferenceexception-in-selenium) – Yevgen Mar 13 '20 at 22:53

1 Answers1

0

As you said, the problem is caused because your code does not let the browser the time it needs to load the webpage. It is compulsory to write a Thread.sleep(x); after each driver.get(myPage); to let the browser load the webpage.

If this does not work for you, try following the answer given to the following question: How to avoid "StaleElementReferenceException" in Selenium?.

ruuben.f
  • 1
  • 1