StaleElementException:
Basically, when you are trying to access the same list on the next page. The previously captured web element is no longer treated as referenced and those referenced web element will throw Exception "Stale Element Exception".
See below code as you are using the same reference stored on the List<WebElement> Productname1
list to access the web element which is not present or is changed due to page refresh or change in the dom.
List<WebElement> Productname = driver.findElements(By.xpath("//tr[@role='row']//td[3]"));
List<WebElement> Productname1 = driver.findElements(By.xpath("//tr[@role='row']//td[3]"));
Basically when all element gets loaded in DOM then Web element gets a referenced web element and as soon as DOM gets reloaded or changed then earlier captured Web element is no longer treated as referenced and those referenced web element will throw error Stale Element Exception.
When you try to interact with the staled WebElement, the StaleElementException is thrown.
Solution:
The simple hack to solve this problem is to update the Weblement list on page refresh/ change or when you move to the next page.
List<WebElement> Productname = driver.findElements(By.xpath("//tr[@role='row']//td[3]"));
int page=0;
for(int i=1;i<Productname.size();i++)
{
page++;
Thread.sleep(2000);
//Update reference
Productname = driver.findElements(By.xpath("//tr[@role='row']//td[3]"));
String title = Productname.get(i).getText();
if(!title.equals("Custom T-Shirt"))
{
driver.findElement(By.xpath("//i[@class='k-icon k-i-arrow-e']")).click();
break;
}
else
{
driver.findElement(By.xpath("//*[@id='products-grid']/tbody/tr[4]/td[1]/input")).click();
break;
}
}
List<WebElement> Productname1 = driver.findElements(By.xpath("//tr[@role='row']//td[3]"));
for(int j=0;j<Productname1.size();j++)
{
//page++;
Thread.sleep(2000);
//Update reference
Productname1 = driver.findElements(By.xpath("//tr[@role='row']//td[3]"));
String title1 = Productname1.get(j).getText();
if(title1.equals("Custom T-Shirt"))
{
driver.findElement(By.xpath("//*[@id='products-grid']/tbody/tr[4]/td[1]/input")).click();
break;
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…