方式1:
WebDriverWait wait= new WebDriverWait(driver, 5 * 60, 1 * 1000); // 显示等待元素出现 wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("fdkasfjdaskljf")));
方式2:
WebDriverWait wait = new WebDriverWait(driver, 60); WebElement xxxx= wait.until(new ExpectedCondition<WebElement>() { @Override public WebElement apply(WebDriver arg0) { return driver.findElement(By.xpath("abcdefg")); } }); xxxx.click();
方式3:
WebDriverWait wait = new WebDriverWait(driver, 60); list = wait.until(new ExpectedCondition<List<WebElement>>() { @Override public List<WebElement> apply(WebDriver arg0) { return driver.findElements(By.xpath("abcdefghijklmn")); } }); 方式4: int counter = 1; //显⽰等待,⽤10s读取元素,如果读取不到将抛出异常,每500ms读取⼀次。 WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10)); bool flag = wait.Until<bool>((d) =>{ Console.WriteLine(counter.ToString()); counter++; return counter == 5; });
"ExpectedConditions.visibilityOfElementLocated"和"ExpectedConditions.presenceOfElementLocated"之间的确切区别是什么?
WebDriverWait wait = new WebDriverWait(driver, 5 * 60, 1 * 1000); wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//a[text()='Show advanced settings...']"))).click(); wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//a[text()='Show advanced settings...']"))).click();
和
visibilityOfElmementLocated检查元素是否存在且是否可见.要检查可见性,请确保元素的高度和宽度大于0.
presenceOfElementLocated只检查dom以查看它是否可以定位元素,无论其可见性如何.
资料来源:https: //selenium.googlecode.com/git/docs/api/java/org/openqa/selenium/support/ui/ExpectedConditions.html#visibilityOf-org.openqa.selenium.WebElement-
visibilityOf public static ExpectedCondition visibilityOf(WebElement element)期望检查已知存在于页面DOM上的元素是否可见.可见性意味着元素不仅会显示,而且高度和宽度也大于0.