packagecom.example.tests;
import staticorg.junit.Assert.*;
import java.util.*;
import org.junit.*;
import org.openqa.selenium.*;
import org.openqa.selenium.ie.InternetExplorerDriver;
public classSelenium2{
WebDriver driver = newInternetExplorerDriver();
JavascriptExecutor jse = (JavascriptExecutor) driver;
@Test
public voidjQueryTest() {
driver.get("http://www.baidu.com/");
injectjQueryIfNeeded();
List<WebElement> elements = (List<WebElement>) jse
.executeScript("return jQuery.find('#nv a')");
assertEquals(7, elements.size()); // 验证超链接的数量
for (inti = 0; i < elements.size(); i++) {
System.out.print(elements.get(i).getText() + "、");
}
driver.close();
}
private voidinjectjQueryIfNeeded() {
if(!jQueryLoaded())
injectjQuery();
}
// 判断是已加载jQuery
publicBoolean jQueryLoaded() {
Boolean loaded;
try{
loaded = (Boolean) jse.executeScript("return "+ "jQuery()!=null");
} catch(WebDriverException e) {
loaded = false;
}
returnloaded;
}
// 通过注入jQuery
public voidinjectjQuery() {
jse.executeScript(" var headID = "
+ "document.getElementsByTagName("head")[0];"
+ "var newScript = document.createElement('script');"
+ "newScript.type = 'text/javascript';" + "newScript.src = "
+ "'http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js';"
+ "headID.appendChild(newScript);");
}
}