【转】Selenium专题—JQuery选择器

juqery选择器是jquery库中非常重要的功能。jquery选择器是基于CSS1-3选择器,加上一些额外的选择器。这些选择器和CSS选择器的使用方法很相似,允许开发人员简单快速的识别页面上的元素。同样可以定位HTML中的元素作为一个单独的元素或者是一个元素的集合。jquery选择器可以使用在那些不支持CSS选择器的浏览器上。

1、使用jquery选择器时需要注意测试的页面有没有加载jquery库

程序清单-判断是否加载jquery库:

package com.Test.function;
 
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
 
//判断测试页面是否加载jquery库,如果没有则手动加载google的在线库
public class JQuery {
    static String url1 = "http://www.baidu.com";
    static String url2 = "http://weibo.kedacom.com";
    static String DriverPath = "F:\\AutoTest\\selenium\\chromedriver.exe";
    static WebDriver driver;
 
    //测试函数
    public static void main(String args[]){
        JQuery j = new JQuery();
        //加载chrome驱动
        System.setProperty("webdriver.chrome.driver",DriverPath);
        driver = new ChromeDriver();
 
        driver.get(url1);
        j.injectJqueryIfNeeded();
        driver.navigate().to(url2);
        j.injectJqueryIfNeeded();
        driver.quit();
    }
 
    //加载jquery
    private void injectJqueryIfNeeded(){
        if(!jqueryIsLoaded()){
            injectJQuery();
        }
    }
 
    /*
     * 判断是否加载jquery
     * 返回true表示已加载jquery
     */
    public Boolean jqueryIsLoaded(){
        Boolean loaded;
        try{
            loaded = (Boolean)((JavascriptExecutor)driver).executeScript("return jQuery()!=null");
            System.out.println("页面本身已加载jquery");
        }catch(Exception e){
            loaded = false;
        }
        return loaded;
    }
 
    //注入jquery
    public void injectJQuery(){
        //在head中拼出加载jquery的html,固定写法
        String jquery = "var headhead\")[0];" +
                        "var newScript = document.createElement('script');" +
                        "newScript.type='text/javascript';" +
                        "newScript.src='http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js';" +
                        "headID.appendChild(newScript);";
        //执行js
        ((JavascriptExecutor)driver).executeScript(jquery);
        System.out.println("手动加载jquery");
    }
}

原文:http://www.ostest.cn/archives/256