首页 > 代码库 > selenium 加载jquery

selenium 加载jquery

 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     @Test
14     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     // 判断是已加载jQuery
34     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     // 通过注入jQuery
45     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 = "http://www.mamicode.com/50                 + "‘http://ajax.googleapis.com/ajax/"
51                 + "libs/jquery/1.7.2/jquery.min.js‘;"
52                 + "headID.appendChild(newScript);");
53     }
54 }

 

selenium 加载jquery