selenium java 中是否存在检查字段

check field is present or not in selenium java

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

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'

该元素给出 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
}

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

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

        return true;
    }

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

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;
        }

    }

如果您考虑每 5 毫秒 timeOutInSeconds=20 和 pollingEveryInMiliSec=5,此方法将搜索给定元素,直到在 20 毫秒内找到它