Selenium 獲取 JavaScript 返回值非常簡單,只需要在 js 腳本中將需要返回的數據 return 就可以,然后通過方法返回 js 的執行結果,方法源碼如下所示:
1 /** 2 * Get Object of return from js 3 * 4 * @author Aaron.ffp 5 * @version V1.0.0: autoSeleniumDemo main.aaron.sele.core SeleniumCore.java execJSR, 2015-8-9 1:39:17 Exp $ 6 * 7 * @param js : return_js 8 * 9 * @return Object 10 */ 11 public Object execJSR(String js){ 12 return ((JavascriptExecutor)this.webdriver).executeScript(js); 13 }
測試步驟概要如下所示:
- 啟動 Chrome 瀏覽器
- 打開易迅網首頁
- 執行 JavaScript 腳本,並獲取返回值
- 關閉頁面
- 退出 WebDriver
方法的測試源碼如下所示:
1 /** 2 * Aaron.ffp Inc. 3 * Copyright (c) 2004-2015 All Rights Reserved. 4 */ 5 package main.aaron.demo.javascript; 6 7 import main.aaron.sele.core.SeleniumCore; 8 9 import org.openqa.selenium.chrome.ChromeDriver; 10 import org.testng.annotations.AfterClass; 11 import org.testng.annotations.BeforeClass; 12 import org.testng.annotations.Test; 13 14 /** 15 * 16 * @author Aaron.ffp 17 * @version V1.0.0: autoSeleniumDemo main.aaron.demo.javascript JQuery.java, 2015-7-27 13:31:31 Exp $ 18 */ 19 public class JQuery extends SeleniumCore{ 20 String jq = "webelement = $('.btn-cor-1')[0]; " + 21 "return webelement.offsetTop + ';' + webelement.offsetLeft + ';' + " + 22 " webelement.offsetHeight + ';' + webelement.offsetWidth"; 23 String baseUrl = "http://www.yixun.com/"; 24 25 @BeforeClass 26 public void beforeClass() throws InterruptedException{ 27 this.webdriver = new ChromeDriver(); 28 this.webdriver.manage().window().maximize(); 29 this.webdriver.get(baseUrl); 30 Thread.sleep(5000); 31 } 32 33 @AfterClass 34 public void afterClass(){ 35 this.webdriver.close(); 36 this.webdriver.quit(); 37 } 38 39 /** 40 * Get return of execute JavaScript 41 * 42 * @author Aaron.ffp 43 * @version V1.0.0: autoSeleniumDemo main.aaron.demo.javascript JQuery.java test_jsReturn, 2015-8-8 15:59:51 Exp $ 44 * 45 */ 46 @Test 47 public void test_jsReturn(){ 48 System.out.println("\nStart test_jsReturn ..."); 49 System.out.println(this.execJSR(jq)); 50 } 51 }
執行結果如下所示:
Start test_jsReturn ... 717;1396;30;100
至此,WebUI 自動化功能測試腳本第 034-JavaScript 在 Selenium 自動化中的應用實例之六(獲取 JS 執行結果返回值) 順利完結,希望此文能夠給初學 Selenium 的您一份參考。
最后,非常感謝親的駐足,希望此文能對親有所幫助。熱烈歡迎親一起探討,共同進步。非常感謝! ^_^
