Selenium2學習-012-WebUI自動化實戰實例-010-解決元素失效:StaleElementReferenceException: stale element reference: element is not attached to the page document


元素失效的想象提示信息如下圖所示,此種問題通常是因為元素頁面刷新之后,為重新獲取元素導致的。

解決此類問題比較簡單,只需要在頁面刷新之后,重新獲取一下元素,就可以消除此種錯誤了。

以下以易迅網搜索為例進行實例代碼演示,希望對各位小主有所啟發,若有不足或錯誤之處,敬請大神指正,不勝感激!

下述代碼中若需消除 StaleElementReferenceException 異常,將 43 行中的注釋取消,重新運行即可。

 1 package main.aaron.demo.javascript;
 2 
 3 import org.openqa.selenium.By;
 4 import org.openqa.selenium.JavascriptExecutor;
 5 import org.openqa.selenium.WebElement;
 6 import org.testng.annotations.Test;
 7 
 8 import main.aaron.sele.core.TestCase;
 9 
10 /**
11  * JavaScript 在 Selenium 自動化中的應用實例
12  * 
13  * @author Aaron.ffp
14  * @version V1.0.0: autoSeleniumDemo main.aaron.demo.javascript JavaScript.java, 2015-6-17 00:24:59 Exp $
15  */
16 public class JavaScript extends TestCase{
17     // 執行 JavaScript 腳本,輸入查詢內容
18     private String jscript = "document.getElementById('q_show').value='iPhone 6 plus'";
19     private String baseUrl = "http://www.yixun.com/";
20     
21     /**
22      * JavaScript 賦值
23      * 
24      * @author Aaron.ffp
25      * @version V1.0.0: autoSeleniumDemo main.aaron.demo.javascript JavaScript.java testJscript, 2015-6-17 12:37:57 Exp $
26      * 
27      * @throws InterruptedException
28      */
29     @Test
30     public void testJscript() throws InterruptedException{
31         this.webdriver.get(this.baseUrl);
32         
33         WebElement search = this.webdriver.findElement(By.cssSelector(".mod_search_btn"));
34         System.out.println(search.getText());
35         this.execJavascript(jscript);
36         
37         
38         WebElement in = this.webdriver.findElement(By.id("q_show"));
39         
40         search.click();
41 
42         // 頁面刷新,需要重新獲取元素,否則會報錯
43         // in = this.webdriver.findElement(By.id("q_show"));
44         
45         System.out.println("現像值 --- q_show.getText() : " + in.getText());
46         
47         this.webdriver.close();
48         this.webdriver.quit();
49     }
50     
51     /**
52      * 執行 JScript 腳本
53      * 
54      * @author Aaron.ffp
55      * @version V1.0.0: autoUISelenium main.java.aaron.sele.core SeleniumCore.java execJavascript, 2015-6-17 00:25:38 Exp $
56      * 
57      * @param jscript 腳本
58      */
59     public void execJavascript(String jscript){
60         ((JavascriptExecutor)this.webdriver).executeScript(jscript);
61     }
62 }
元素失效演示:StaleElementReferenceException

至此,WebUI 自動化功能測試腳本第 010 篇-解決元素失效:StaleElementReferenceException 順利完結,希望此文能夠給初學 Selenium 的您一份參考。

最后,非常感謝親的駐足,希望此文能對親有所幫助。熱烈歡迎親一起探討,共同進步。非常感謝! ^_^

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM