WebDriver中使用JQuery选择器
1. 在已加载了JQuery的页面上可以直接使用JQuery选择器
例如www.jquery.com网站,如果我们想定位红框中导航栏中的偶数为就可以使用jquery的伪选择器:even
具体实现如下 package com.example.tests; import static org.junit.Assert.*; import java.util.*; import org.junit.*; import org.openqa.selenium.*; import org.openqa.selenium.ie.InternetExplorerDriver; public class test { WebDriver driver = new InternetExplorerDriver(); JavascriptExecutor jse = (JavascriptExecutor)driver; @Test public void jQueryTest() { driver.get("http://www.jquery.com/"); //在executeScript中调用jQuery.find(jquerySelector); List<WebElement> elements = (List<WebElement>)jse.executeScript("return jQuery.find" +"('.menu-item a:even')"); assertEquals(3,elements.size()); assertEquals("Download",elements.get(0).getText()); assertEquals("Blog",elements.get(1).getText()); assertEquals("Browser Support",elements.get(2).getText()); driver.close(); } }
2. 另一种情况就是页面没有另载jQuery,我们需要先 判断再自已手动注入,以百度为例,百度首页是没有加载的
package com.example.tests; import static org.junit.Assert.*; import java.util.*; import org.junit.*; import org.openqa.selenium.*; import org.openqa.selenium.ie.InternetExplorerDriver; public class Selenium2{ WebDriver driver = new InternetExplorerDriver(); JavascriptExecutor jse = (JavascriptExecutor) driver; @Test public void jQueryTest() { driver.get("http://www.baidu.com/"); injectjQueryIfNeeded(); List<WebElement> elements = (List<WebElement>) jse .executeScript("return jQuery.find('#nv a')"); assertEquals(7, elements.size()); // 验证超链接的数量 for (int i = 0; i < elements.size(); i++) { System.out.print(elements.get(i).getText() + "、"); } driver.close(); } private void injectjQueryIfNeeded() { if (!jQueryLoaded()) injectjQuery(); } // 判断是已加载jQuery public Boolean jQueryLoaded() { Boolean loaded; try { loaded = (Boolean) jse.executeScript("return " + "jQuery()!=null"); } catch (WebDriverException e) { loaded = false; } return loaded; } // 通过注入jQuery public void injectjQuery() { jse.executeScript(" var headID = " + "document.getElementsByTagName(\"head\")[0];" + "var newScript = document.createElement('script');" + "newScript.type = 'text/javascript';" + "newScript.src = " + "'http://ajax.googleapis.com/ajax/" + "libs/jquery/1.7.2/jquery.min.js';" + "headID.appendChild(newScript);"); } }