I have the following table in my page (.html):
<table>
<thead>
<td>Id</td>
<td>Descricao</td>
<td>Quant</td>
<td>Preco</td>
<td>Acoes Disponiveis</td>
</thead>
<tbody>
<tr>
<td>1</td>
<td>Item Produto XMasInicial</td>
<td>20</td>
<td>2.30</td>
<td>
<a href="passoInicial.html">Cadastrar Outro</a>
<a href="passoInicial.html"><img src="exit.png" /></a>
</td>
</tr>
<tr>
<td>2</td>
<td>Item Produto XMasFinal</td>
<td>50</td>
<td>1.90</td>
<td>
<a href="passoFinal.html">Ficar na mesma</a>
<a href="passoFinal.html"><img src="exit.png" /></a>
</td>
</tr>
<tr>
<td>3</td>
<td>Item Produto XMasGoogle</td>
<td>50</td>
<td>1.90</td>
<td>
<a href="paginaVazia.html">Ir para o Google</a>
<a href="paginaVazia.html"><img src="exit.png" /></a>
</td>
</tr>
</tbody>
</table>
I need to test this page: the click in the "exit.png" image (that's a link). I write the following piece of code (in a for statement, from i=0 to 2), but it is not working:
List<WebElement> imgLinks = this.webDriver.findElements(By.xpath("//img[contains(@src,'exit.png')]"));
for(...) {
imgLinks.get(i).click();
//some code to return for this html page (back) and click in the next image...
}
The result is the following error:
org.openqa.selenium.StaleElementReferenceException: stale element reference: element is not attached to the page document
I used //a/img[contains(@src,'exit.png')] instead of //img[contains(@src,'exit.png')] , but it doesn't work any away.
How can I fix this problem?
The issue is that when you click a link, the collection of links in imgLinks
immediately becomes stale. Going back to the page, and trying to interact with the imgLinks
list is going to result in a state element reference error.
This approach should work for you. It will get a new list each time you return to the page.
List<WebElement> imgLinks = this.webDriver.findElements(By.xpath("//img[contains(@src,'exit.png')]"));
int imgLinksLength = imgLinks.size();
for(int i = 0; i < imgLinksLength ; i++) {
List<WebElement> imgLinks = this.webDriver.findElements(By.xpath("//img[contains(@src,'exit.png')]"));
imgLinks.get(i).click();
//some code to return for this html page (back) and click in the next image...
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.