3-web自动化-元素等待

//2秒内加载下面的url,超时会报错 
driver.manage().timeouts().pageLoadTimeout(2, TimeUnit.SECONDS);
 driver.get("https://www.sina.com.cn/");
 driver.findElement(By.linkText("新闻")).click();

隐式等待

 driver.get("https://www.sina.com.cn/");
 driver.manage().timeouts().implicitlyWait(5,TimeUnit.SECONDS);//隐式等待10s,“新闻”链接
 driver.findElement(By.linkText("新闻1")).click();

显示等待

 

 /**
     * 获取元素已加载到document树里的元素
     * @param by
     * @param seconds
     * @return
     */
    public WebElement getElementLocatedElement(By by,long seconds){
        WebDriverWait driverWait=new WebDriverWait(driver,seconds);//显示等待10s,默认500毫秒查找一次
        try {
            WebElement webElement=driverWait.until(ExpectedConditions.presenceOfElementLocated(by));
            return webElement;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    /**
     * 获取可见元素。
     * @param by
     * @return
     */
    public WebElement getVisibilyElement(By by){
        WebDriverWait driverWait=new WebDriverWait(driver,10);//显示等待10s,默认500毫秒查找一次
        try {
            WebElement webElement=driverWait.until(ExpectedConditions.visibilityOfElementLocated(by));
            return webElement;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    /**
     * 获取
     * @param by
     * @return
     */
    public WebElement getElement(By by){
        WebDriverWait driverWait=new WebDriverWait(driver,10);//显示等待30s,默认500毫秒查找一次
        try {
            String jsStr="return document.readyState=='complete'";//js判断文档加载完成
            boolean isReady= (boolean) driverWait.until(ExpectedConditions.jsReturnsValue(jsStr));
            if (isReady){
                return getVisibilyElement(by);
            } 
            return null;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @Test
    public void test1() throws InterruptedException {
        driver.get("https://www.sina.com.cn/");
        getElement(By.linkText("新闻"),20).click();
    }

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值