如何在Java中使用Selenium Webdriver检测元素的存在

如何在Java中使用Selenium Webdriver检测元素的存在,java,selenium,selenium-webdriver,Java,Selenium,Selenium Webdriver,我想使用Selenium WebDriver的findElement()函数来检测页面上是否存在元素。无论我做什么,Selenium都会退出代码,即使我抛出WebDriverException 我尝试使用此代码,但它没有阻止Selenium退出: if(driver.findElement(By.xpath(xpath) != null){ driver.findElement(By.xpath(xpath)).click(); System.out.println("Eleme

我想使用Selenium WebDriver的
findElement()
函数来检测页面上是否存在元素。无论我做什么,Selenium都会退出代码,即使我抛出WebDriverException

我尝试使用此代码,但它没有阻止Selenium退出:

if(driver.findElement(By.xpath(xpath) != null){
    driver.findElement(By.xpath(xpath)).click();
    System.out.println("Element is Present");
}else{
    System.out.println("Element is Absent");
}
我做错了什么


isDisplayed()
似乎也有类似的错误。我只是使用了错误的方法还是使用了错误的方法?

是的,您可以使用findElements。我在下面给你写了一个例子:

public WebElement element(WebDriver driver) {
    List<WebElement> list = driver.findElements(By.xpath("xpath"));
    if (list != null && !list.isEmpty()) {
        return list.get(0);
    }
    return null;
}
element.click();
公共WebElement元素(WebDriver){
List=driver.findElements(By.xpath(“xpath”);
if(list!=null&&!list.isEmpty()){
返回列表。获取(0);
}
返回null;
}
元素。单击();

您应该创建一个等待元素的方法,如果元素存在或不存在,则返回true或false。这应该能帮你做到-

public boolean isElementPresent(final String xpath) {
    WebDriverWait wait = new WebDriverWait(driver, 30);
    try {
    return wait.until(new ExpectedCondition<Boolean>() {
            public Boolean apply(WebDriver driver) {
                if (driver.findElement(By.xpath(xpath)).isDisplayed()) {
                    return true;
                } else {
                    return false;
                }
            }
        });         
    } catch (NoSuchElementException | TimeoutException e) {         
        System.out.println("The wait timed out, couldnt not find element");
        return false;
    }               
}
所以本质上,

如果isElementPresent==true-->单击该元素
或者打印一些东西

使用driver.findElements()。复数形式。它将返回一个列表。检查尺寸。如果元素不存在,findElement会抛出一个异常。@Grasshopper它工作得很好,谢谢否决票,我不想我的新帐户被禁止,我想我有一个很好的问题,我找不到一个对我有用的答案。@KenBone一次否决票不会造成多大伤害-要被禁止,一个人应该会得到很多否决票。工作得很好,我不知道为什么WebDriver不能正确地抛出异常,但这样就可以了。
if (isElementPresent("xpath")) {
driver.findElement(By.xpath(xpath)).click();
} else {
    System.out.println("Can't click on the element because it's not there");
}