(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