【selenium3+JAVA】界面自动化测试教程(五)——等待设置

超时设置分为三种,分别为显性等待,隐性等待和强制等待,如下所示:

1、隐式等待

此等待方式为全局共用,此处共有三个方法,分别为查找元素的等待超时时间、页面加载等待超时时间和js脚本运行超时时间,方法如下代码所示

System.setProperty("webdriver.chrome.driver", "D:\\test\\driver\\chromedriver.exe");
ChromeDriver chrome = new ChromeDriver();
//此处为设定页面加载超时时间为30s
chrome.manage().timeouts().pageLoadTimeout(30, TimeUnit.SECONDS);
//此处为设定元素查找最长超时时间为10s
chrome.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
//此处为设置js脚本运行超时时间为30s
chrome.manage().timeouts().setScriptTimeout(30, TimeUnit.SECONDS);

2、强制等待

此种等待方法直接调用Thread.sleep()方法来进行线程等待,由于此方法较为死板,不够灵活,会导致脚本运行时间变长,故建议尽量少用,封装方法如下:

public static void wait(int second) 
    {
    	try {
			Thread.sleep(second*1000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }

3、显式等待

此种方式用于特定元素、特定条件的等待,使用灵活,建议使用这种方法来进行等待设置,基本操作操作方法如下:

System.setProperty("webdriver.chrome.driver", "D:\\test\\driver\\chromedriver.exe");
ChromeDriver chrome = new ChromeDriver();
try {
    WebDriverWait wait = new WebDriverWait(chrome, 10, 100);
    // 每隔100毫秒去调用一下until中的函数,默认是0.5秒,如果等待10秒还没有找到元素 。则抛出异常。
    wait.until(new ExpectedCondition<WebElement>() {
    	public WebElement apply(WebDriver driver) {
    		driver.findElement(By.id("kw"));
    		return driver.findElement(By.id("kw"));
    		}
    }).sendKeys("我是一个自动化测试小脚本");
    } finally {
    		chrome.close();
    }

查看源码我们可以看到如下代码:

/**
   * Wait will ignore instances of NotFoundException that are encountered (thrown) by default in
   * the 'until' condition, and immediately propagate all others.  You can add more to the ignore
   * list by calling ignoring(exceptions to add).
   *
   * @param driver The WebDriver instance to pass to the expected conditions
   * @param timeOutInSeconds The timeout in seconds when an expectation is called
   * @see WebDriverWait#ignoring(java.lang.Class)
   */
  public WebDriverWait(WebDriver driver, long timeOutInSeconds) {
    this(
        driver,
        java.time.Clock.systemDefaultZone(),
        Sleeper.SYSTEM_SLEEPER,
        timeOutInSeconds,
        DEFAULT_SLEEP_TIMEOUT);
  }

如上方法中只有driver参数和timeout参数,其他几个参数都是在函数内部设置的默认参数,Clock和Sleeper都是使用系统默认,而DEFAULT_SLEEP_TIMEOUT则使用的如下这个,500ms:

protected final static long DEFAULT_SLEEP_TIMEOUT = 500;

其他几个方法大同小异,区别在于参数变为输入的了,故一般使用前面给出的列子中的那个方法就好;
本例子中给出的是自己自定义until中的condition,但是实际上selenium已经提供了一些常用的条件,放在类ExpectedConditions中,如下所示;
condition
这些方法基本上通过名字就可以看出来其大致用途,所以此处就不再详述了,使用方法参考如下代码:

System.setProperty("webdriver.chrome.driver", "D:\\test\\driver\\chromedriver.exe");
ChromeDriver chrome = new ChromeDriver();
//如下为超时时间为10s,查询间隔时间为100ms
WebDriverWait wait = new WebDriverWait(chrome, 10, 100);
wait.until(ExpectedConditions.alertIsPresent());

猜你喜欢

转载自blog.csdn.net/df0128/article/details/82823674