The most obvious issue with this line of code is the lack of synchronization.
findElement() attempts finding the element in the DOM of the page. If the element is in the DOM, it is returned. If the element is not in the DOM, findElement() generates an exception.
The solution for this problem is adding synchronization with an explicit wait and an expected condition:
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(60));
wait.until(ExpectedConditions.visibilityOfElementLocated(nameBy));
String name = driver.findElement(nameBy).getText();
This time, if the element is not in the DOM of the page, the code waits until the element is in the DOM and it is visible. If this does not happen in 60 seconds, an exception is generated.
But there is another problem that may be happening.
It is also possible that the name element is in the DOM and is also visible. But its value is not available right away. Initially, the value of the element is empty and it changes to a valid text value in some time.
When this happens, the name variable gets an empty String value which is not what we would like to happen.
The solution for this second issue is to wait until the name value is not empty.
There are multiple expected conditions about the text of an element in the ExpectedConditions class:
textToBe(By locator, String value)
textToBePresentInElement(WebElement element, String text)
textToBePresentInElementLocated(By locator, String text)
textToBePresentInElementValue(By locator, String text)
textToBePresentInElementValue(WebElement element, String text)
None of these works since we do not know what value the name element will have.
We can, however, wait until the name value is not empty:
WebDriverWait wait = new WebDriverWait(driver, Durtion.ofSeconds(60));
wait.until(ExpectedConditions.visibilityOfElementLocated(nameBy));
wait.until(ExpectedConditions.not(ExpectedConditions.textTobe(nameBy, "")));
String name = driver.findElement(nameBy).getText();
Thanks for reading.