java 查找元素是否存在_java - WebDriver:检查元素是否存在?

我扩展了Selenium WebDriver实现,在我的案例中是HtmlUnitDriver来公开一个方法

public boolean isElementPresent(By by){}

像这样:

检查页面是否在超时期限内加载。

加载页面后,我将WebDriver的隐式等待时间降低到几毫秒,在我的情况下为100毫秒,可能也应该使用0工厂。

调用findElements(By),WebDriver即使找不到元素也只会等待上面的时间量。

提升未来页面加载的隐含等待时间

这是我的代码:

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;

import org.openqa.selenium.JavascriptExecutor;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.htmlunit.HtmlUnitDriver;

import org.openqa.selenium.support.ui.ExpectedCondition;

import org.openqa.selenium.support.ui.WebDriverWait;

public class CustomHtmlUnitDriver extends HtmlUnitDriver {

public static final long DEFAULT_TIMEOUT_SECONDS = 30;

private long timeout = DEFAULT_TIMEOUT_SECONDS;

public long getTimeout() {

return timeout;

}

public void setTimeout(long timeout) {

this.timeout = timeout;

}

public boolean isElementPresent(By by) {

boolean isPresent = true;

waitForLoad();

//search for elements and check if list is empty

if (this.findElements(by).isEmpty()) {

isPresent = false;

}

//rise back implicitly wait time

this.manage().timeouts().implicitlyWait(timeout, TimeUnit.SECONDS);

return isPresent;

}

public void waitForLoad() {

ExpectedCondition pageLoadCondition = new ExpectedCondition() {

public Boolean apply(WebDriver wd) {

//this will tel if page is loaded

return "complete".equals(((JavascriptExecutor) wd).executeScript("return document.readyState"));

}

};

WebDriverWait wait = new WebDriverWait(this, timeout);

//wait for page complete

wait.until(pageLoadCondition);

//lower implicitly wait time

this.manage().timeouts().implicitlyWait(100, TimeUnit.MILLISECONDS);

}

}

用法:

CustomHtmlUnitDriver wd = new CustomHtmlUnitDriver();

wd.get("http://example.org");

if (wd.isElementPresent(By.id("Accept"))) {

wd.findElement(By.id("Accept")).click();

}

else {

System.out.println("Accept button not found on page");

}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值