First of all using the correct xpath is an important step to remove the the NoSuchElementException.The xpath for identifying the element is
//p[text()='Animal Crossing: New Horizons']//following-sibling::p[@class='price-small']//span[@data-price]
Even if this doesn’t identify then there might be some timing issues with the webpage i.e.
the page is still being rendered and you've already finished your element search and obtained no element exception.
You can use FluentWait to overcome this problem.
Let’s say you have an element which sometimes appears in just 1 second and sometimes it takes minutes to appear. In that case it is better to define an explicit wait using FluentWait, as this will try to find an element again and again until it finds it or until the final timer runs out.
An instance of FluentWait can be defined to configure the maximum amount of time to wait for a condition as well as the frequency at which the condition must be checked.User can also configure the wait to ignore specific types of exceptions while waiting for an element, such as NoSuchElementExceptions on the page.
// Waiting 30 seconds for an element to be present on the page, checking
// for its presence once every 5 seconds.
Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)
.withTimeout(30, SECONDS);
.pollingEvery(5, SECONDS) ;
.ignoring(NoSuchElementException.class);
Adding explicit wait might also do the trick:
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
. . .
WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement element = wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("element_xpath"))); element.click();