When navigating from one webpage to another you need to wait for the element's presence / visibility before performing any operations on it.
public WebElement find(WebDriver driver, By locator) {
WebElement element = null;
// Maximum number of retries
int retry = 3;
// Timeout for a single try
int timeoutInSeconds = 3;
do {
// Initialize wait on the defined web driver
WebDriverWait wait = new WebDriverWait(driver, timeoutInSeconds);
// Wait until the visibility of the web element based on locator
wait.until(ExpectedConditions.visibilityOfElementLocated(locator));
// If element is present, then it findElement() will return size()>0
if(driver.findElements(locator).size() > 0) {
// Store the first instance of the web element
// Similar to using driver.findElements(locator).get(0);
element = driver.findElement(locator);
}
// If element is found
if(element!=null) {
// exit do-while loop
break;
} else {
// retry again
retry--;
}
// stop retrying if the element is found or there are no retries left
} while(element!=null && retry>0);
// return the element (if not found will return null)
return element;
}