Selenium 智能等待的补充

之前再讲解Selenium 元素等待时,丢过一个问题,怎么才能再项目中真正做到智能等待呢?
其实这里我们需要自己对框架进行简单二次封装。

想达到这效果有两种方式:

  1. 重新封装常用的动作,封装的每个动作都加上等待,这样你写case时调用自己封装的方法自然就会等待
WebDriverWait wait = new WebDriverWait(driver, 30);
wait.until(ExpectedConditions.presenceOfElementLocated(by));
driver.click();

上面这种方式可以达到效果,但是麻烦了点,这里教另一种方式,虽然同样要重写每个常用方法,但是代码量会少很多。

  1. 细想下,我们查找元素都是通过findElement 或者 findElements 方法对吧。 那如果我们重新封装下findElement 让这个方法去等待元素加载是不是就方便很多了。

我们具体看下重新封装findElement方法:

import com.frame.logger.LoggerControler;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.WebDriverWait;

import java.util.List;

/**
 * Created by 米阳 on 2017/10/16.
 */
public class Find extends SeleniumDriver{
    final static LoggerControler log = LoggerControler.getLogger(Find.class);


    public static WebElement findElement(final By by) {
        WebElement webElement = null;
        try {
            webElement = new WebDriverWait(driver, 10).until(new ExpectedCondition<WebElement>() {
                public WebElement apply(WebDriver driver) {
                    return driver.findElement(by);
                }
            });
        } catch (Exception e) {
            log.error("元素:" + by + "查找超时");
            e.printStackTrace();
        }
        return webElement;
    }

    public static List<WebElement> findElements(final By by) {
        List<WebElement> webElement = null;
        try {
            webElement = new WebDriverWait(driver, 10).until(new ExpectedCondition<List<WebElement>>() {
                public List<WebElement> apply(WebDriver driver) {
                    return driver.findElements(by);
                }
            });
        } catch (Exception e) {
            log.error("元素:" + by + "查找超时");
            e.printStackTrace();
        }
        return webElement;
    }
}

接着我们重新封装我们的常用操作方法:

  public static void click(By by, String... text) {
        Find.findElement(by).click();
        if (text.length > 0) {
            log.info("点击:" + text[0]);
        } else {
            log.info("点击:" + by);
        }

    }

    public static void clear(By by) {
        Find.findElement(by).clear();
        log.info("清空" + by);
    }

    public static void sendText(By by, String text) {
        WebElement element = Find.findElement(by);
        element.clear();
        element.sendKeys(text);
        log.info("在" + by + "输入" + text);
    }

这样以后再写Case时就可以直接调用自己封装的动作方法了:

    public void sendKeysPWD() {
        Action.clear(pwdFiled);//pwdFiled 定位方式
        Action.sendText(pwdFiled, "pwd");
    }

最后我之前授课时简单对Selenium做了二次封装,集成了 log4j ,testng,extentreports(一个很漂亮的报告)大伙可以参考,这个框架有个很大问题,driver静态的,所以无法实现并发。。。 大家有兴趣自己搞搞。
https://github.com/MeYoung/WebUIAutomation_Selenium

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容