標籤:drive query ++ ade out nts example document open
1 packagecom.example.tests; 2 3 import staticorg.junit.Assert.*; 4 importjava.util.*; 5 importorg.junit.*; 6 importorg.openqa.selenium.*; 7 importorg.openqa.selenium.ie.InternetExplorerDriver; 8 9 public classSelenium2{10 WebDriver driver = newInternetExplorerDriver();11 JavascriptExecutor jse = (JavascriptExecutor) driver;12 13 @Test14 public voidjQueryTest() {15 driver.get("http://www.baidu.com/");16 injectjQueryIfNeeded();17 18 List<WebElement> elements = (List<WebElement>) jse.executeScript("return jQuery.find(‘#nv a‘)");19 20 assertEquals(7, elements.size()); // 驗證超連結的數量21 for (inti = 0; i < elements.size(); i++) {22 System.out.print(elements.get(i).getText() + "、");23 }24 25 driver.close();26 }27 28 private voidinjectjQueryIfNeeded() {29 if(!jQueryLoaded())30 injectjQuery();31 }32 33 // 判斷是已載入jQuery34 publicBoolean jQueryLoaded() {35 Boolean loaded;36 try{37 loaded = (Boolean) jse.executeScript("return "+ "jQuery()!=null");38 } catch(WebDriverException e) {39 loaded = false;40 }41 returnloaded;42 }43 44 // 通過注入jQuery45 public voidinjectjQuery() {46 jse.executeScript(" var headID = "47 + "document.getElementsByTagName(\"head\")[0];"48 + "var newScript = document.createElement(‘script‘);"49 + "newScript.type = ‘text/javascript‘;" + "newScript.src = "50 + "‘http://ajax.googleapis.com/ajax/"51 + "libs/jquery/1.7.2/jquery.min.js‘;"52 + "headID.appendChild(newScript);");53 }54 }
selenium 載入jquery