Clase de herramienta de espera de elementos Java + Selenium

Cuando usamos generalmente el rastreador de selenio, generalmente encontramos la operación de inicio de sesión. Sin embargo, cuando el ganso inicia sesión, si el tiempo de respuesta del servidor de la otra parte es demasiado largo o demasiado rápido, el tiempo es inestable, entonces la verificación de inicio de sesión se realiza en este momento y la contraseña es correcta. Cuando la información se completa correctamente, será muy problemático.

Después de verificar mucha información, todavía no pude encontrar un método de espera de elementos satisfactorio, así que simplemente implementé uno por mí mismo y lo compartí con ustedes aquí.

Función descriptiva

función Descripción
waitElement () Esperando el elemento especificado. Pase el objeto WebDriver y el objeto By de selenium. Si el objeto existe, ejecute la devolución de llamada o lance una excepción
waitUrl () Esperando la página especificada. Pase el objeto WebDriver y la URL de la página web. Si el objeto existe, ejecute la devolución de llamada o lance una excepción
waitElementText () Espere el texto del elemento especificado. Pase el objeto WebDriver, el objeto By de selenium y el texto que se va a juzgar. Si el texto existe, ejecute la devolución de llamada o lance una excepción

Código fuente

Categoria principal

/**
 * @Author: KL-Skeleton
 * @Description: ${Description}
 * @Date: Created in 19:22 2020/8/27
 */
public class ElementTimeOutUtils {
    
    
//线程的超时时间默认为一分钟
    private static long runnable_timeout = 60*1000;
    /**
     *线程池
     */
    private static ExecutorService cachedThreadPool = Executors.newCachedThreadPool();

    //抛出错误的语句
    private  static  String exceptionStr(WebDriver driver,Object by){
    
    
        return "the " + driver + " time out waiting for the element(" + by+")";
    }

    //元素等待
    public static void waitElement(WebDriver driver, By by, long time) throws ElementTimeOutException {
    
    

        long beginTime = System.currentTimeMillis();
        //如果当前时间减去开始的时间,小于time,并且传入的等待条件不符合,那么将一直堵塞此进程,直到超时,或者条件符合即可。
        while ((System.currentTimeMillis()-beginTime<time)&&(driver.findElements(by).size()==0)){
    
    }
        if(System.currentTimeMillis()-beginTime>=time){
    
    
            throw new ElementTimeOutException(exceptionStr(driver,by));
        }

    }

    public static void waitElement(WebDriver driver, By by,MyRunnable runnable){
    
    
        cachedThreadPool.execute(()->{
    
    
            long beginTime = System.currentTimeMillis();
            //如果当前时间减去开始的时间,小于time,并且传入的等待条件不符合,那么将一直堵塞此进程,直到超时,或者条件符合即可。
            while ((System.currentTimeMillis()-beginTime<runnable_timeout)&&(driver.findElements(by).size()==0)){
    
    }
            if(System.currentTimeMillis()-beginTime<runnable_timeout){
    
    
                runnable.run();
            }else  {
    
    
                runnable.timeout();
            }
        });

    }


    //网页等待
    public static void waitUrl(WebDriver driver,String url,long time) throws ElementTimeOutException{
    
    
        long beginTime = System.currentTimeMillis();
        //如果当前时间减去开始的时间,小于time,并且传入的等待条件不符合,那么将一直堵塞此进程,直到超时,或者条件符合即可。
        while ((System.currentTimeMillis()-beginTime<time)&&(!driver.getCurrentUrl().contains(url))){
    
    }
        if(System.currentTimeMillis()-beginTime>=time){
    
    
            throw new ElementTimeOutException(exceptionStr(driver,url));
        }
    }


    public static void waitUrl(WebDriver driver, String url, MyRunnable runnable){
    
    
        cachedThreadPool.execute(()->{
    
    
            long beginTime = System.currentTimeMillis();
            //如果当前时间减去开始的时间,小于time,并且传入的等待条件不符合,那么将一直堵塞此进程,直到超时,或者条件符合即可。
            while ((System.currentTimeMillis()-beginTime<runnable_timeout)&&(!driver.getCurrentUrl().contains(url))){
    
    }
            if(System.currentTimeMillis()-beginTime<runnable_timeout) {
    
    
                runnable.run();
            }else {
    
    
                runnable.timeout();
            }
        });
    }

    //文本等待
    public static void waitElementText(WebDriver driver, By by, String text, long time) throws ElementTimeOutException{
    
    
        long beginTime = System.currentTimeMillis();
        //如果当前时间减去开始的时间,大于time,并且传入的布尔值为false。则抛出异常。
        while ((System.currentTimeMillis()-beginTime<time)&&(!driver.findElements(by).get(0).getText().contains(text))){
    
    }
        if(System.currentTimeMillis()-beginTime>=time){
    
    
            throw new ElementTimeOutException(exceptionStr(driver,by+" and text:"+text));
        }
    }


    public static void waitElementText(WebDriver driver,  By by,String text,MyRunnable runnable){
    
    
        cachedThreadPool.execute(()->{
    
    
            long beginTime = System.currentTimeMillis();
            //如果当前时间减去开始的时间,小于time,并且传入的等待条件不符合,那么将一直堵塞此进程,直到超时,或者条件符合即可。
            while ((System.currentTimeMillis()-beginTime<runnable_timeout)&&(!driver.findElements(by).get(0).getText().contains(text))){
    
    }
            if(System.currentTimeMillis()-beginTime<runnable_timeout){
    
    
                runnable.run();
            } else  {
    
    
                runnable.timeout();
            }
        });
    }

    //geter and seter
    public static long getRunnable_timeout() {
    
    
        return runnable_timeout;
    }

    public static void setRunnable_timeout(long runnable_timeout) {
    
    
        ElementTimeOutUtils.runnable_timeout = runnable_timeout;
    }

    public abstract static class MyRunnable{
    
    
        public void run(){
    
    }
        public void timeout(){
    
    }
    }





}

Clase de excepción

public   class ElementTimeOutException extends  Exception{
    
    
    public ElementTimeOutException() {
    
    
        super();
    }

    public ElementTimeOutException(String message) {
    
    
        super(message);
    }
}

Ejemplo de uso

Baidu simula la búsqueda, ingrese "a" en el cuadro de búsqueda y luego haga clic en buscar hasta que se cargue el elemento inferior "content_bottom", entonces se puede realizar la devolución de llamada. Si la búsqueda es lenta durante más de 1 minuto debido a razones de la red, o el elemento "content_bottom" no se encuentra, entonces Ejecute la devolución de llamada de tiempo de espera.

public static void main(String[] args) {
    
    

        System.setProperty("webdriver.chrome.driver","C:\\Users\\ASUS\\Desktop\\chromedriver7.9.exe");
        WebDriver driver = new ChromeDriver();
        driver.get("https://www.baidu.com/");
        driver.findElement(By.id("kw")).sendKeys("a");
        driver.findElement(By.id("su")).click();
        //方法一:开启元素等待线程,最大等待时间默认为1分钟,这里可以设置为10秒,
        //优点:不会阻塞进程
        ElementTimeOutUtils.setRunnable_timeout(10*1000);
        ElementTimeOutUtils.waitElement(driver, By.id("content_bottom"), new ElementTimeOutUtils.MyRunnable() {
    
    
            @Override
            public void run() {
    
    
                System.out.println("百度搜索加载成功");
            }
            @Override
            public void timeout() {
    
    
                super.timeout();
                System.out.println("百度搜索加载失败");
            }
        });

        //方法二:不开启线程,指定超时时间5秒,如果超时,则抛出异常
        //缺点:会阻塞进程
        try {
    
    
            ElementTimeOutUtils.waitElement(driver, By.id("content_bottoms"),5000);
            System.out.println("百度搜索加载成功");
        } catch (ElementTimeOutException e) {
    
    
            System.out.println("百度搜索加载失败");
            e.printStackTrace();
        }

    }

resultado de la operación:
Inserte la descripción de la imagen aquí

  • Lo mismo también se puede utilizar para determinar si la contraseña de la cuenta es incorrecta al iniciar sesión, etc.
TimeOutUtil.waitElementText(driver, By.id("show_error"),"验证码错误", new TimeOutUtil.MyRunnable() {
    
    
            @Override
            public void run() {
    
    
                System.out.println("验证码错误");
            }
        });

Supongo que te gusta

Origin blog.csdn.net/qq_31254489/article/details/108267115
Recomendado
Clasificación