在selenium java中是否存在check字段

问题描述 投票:0回答:3

我需要查找是否显示元素。如何在selenium web驱动程序中检查?

if(driver.findElement(By.id("p_first_name")).isDisplayed()) 

      {

        WebElement fname =driver.findElement(By.id("p_first_name"));
        fname.sendKeys("pradnya");

        WebElement lname = driver.findElement(By.xpath("//*[@id=\"p_last_name\"]"));
        lname.sendKeys("Bolli");

        WebElement Address1 = driver.findElement(By.xpath("//*[@id=\"address_11\"]"));
        Address1.sendKeys("New address1");

        WebElement Address2 = driver.findElement(By.xpath("//*[@id=\"address_21\"]"));
        Address2.sendKeys("New address2");

        WebElement City = driver.findElement(By.xpath("//*[@id=\"city1\"]"));
        City.sendKeys("Pune");

        WebElement Country = driver.findElement(By.xpath("//*[@id=\"country1\"]"));
        Country.sendKeys("India");

        WebElement ZipCode = driver.findElement(By.xpath("//*[@id=\"pincode1\"]"));
        ZipCode.sendKeys("India");

        WebElement State = driver.findElement(By.xpath("//*[@id=\"bds\"]"));
        State.sendKeys("Maharashtra");

        }   
    else 
        {
        WebElement address = driver.findElement(By.xpath("//*[@id=\"update_add77\"]"));
        address.click();
        }

在结帐页面上首先显示地址表单,当用户填写时,显示列表。列表显示时,地址表单未显示。在这种情况下,如何检查是否显示地址表单字段?

我使用上面的代码,但它给了我异常消息

 'Unable to locate element: #p_first_name'
selenium selenium-webdriver automated-tests browser-automation
3个回答
3
投票

该元素提供NoSuchElementException,因为在您尝试使用isDisplayed()方法找到它的UI上不存在该元素。

因此,要解决您的问题,您应该获取元素的列表,然后可以获取该列表的大小,如果大小大于0,则表示该元素存在于页面上,否则该元素不存在。 您需要在代码中进行以下更改:

if(driver.findElements(By.id("p_first_name")).size()>0){
  // Add the if code here
}
else{
  // Add the else code here
}

0
投票

您可以创建此类检查的方法。我们使用NoSuchElementException来验证元素不存在。

public boolean isElementExist(By locator)
    {
        try {
            driver.findElement(locator);
        } catch (NoSuchElementException e) {
            return false;
        }

        return true;
    }

或者由于缓慢的加载和超时,我建议使用*WebDriverWait*


0
投票
public boolean isElementPresent(By element,int timeOutInSeconds,int pollingEveryInMiliSec) {
        try {
        WebDriverWait wait = new WebDriverWait(d, timeOutInSeconds);
            wait.pollingEvery(pollingEveryInMiliSec, TimeUnit.MILLISECONDS);
            wait.ignoring(NoSuchElementException.class);
            wait.ignoring(ElementNotVisibleException.class);
            wait.ignoring(StaleElementReferenceException.class);
            wait.ignoring(NoSuchFrameException.class);
        wait.until(ExpectedConditions.visibilityOfElementLocated(element) ));
        return true;
        }
        catch(Exception e) {
            return false;
        }

    }

如果你考虑timeOutInSeconds = 20并且每5毫秒pollingEveryInMiliSec = 5,这个方法将搜索给定元素,直到它在20ms内找到它

© www.soinside.com 2019 - 2024. All rights reserved.