IF条件未按预期工作

时间:2017-09-17 17:23:46

标签: java selenium selenium-webdriver selenium-chromedriver

for(int row=1; row <= 6; row++)
{
    WebDriver driver=new ChromeDriver();
    driver.manage().deleteAllCookies();
    driver.get("http:/path/");
    driver.manage().window().maximize();
    String username = s.getCell(2,row).getContents();
    System.out.println("Username: "+username);
    driver.findElement(By.id("j_username_leftAside")).sendKeys(username);
    String password= s.getCell(3,row).getContents();
    System.out.println("Password: "+password);
    driver.findElement(By.id("j_password_leftAside")).sendKeys(password);
    driver.findElement(By.xpath("/html[@class=' js opacity generatedcontent pointerevents']/body[@class='page-homepage pageType-ContentPage template-pages-layout-RexelHomePageLayout pageLabel-homepage language-de ']/div[@id='page']/div[@id='content']/div[@id='content']/div[@class='content-top-inner']/div[@id='content-inner']/div[@class='mid-wrapper'][1]/div[@class='yCmsContentSlot']/div[@class='login clear']/form[@id='loginForm']/div[@class='left sign-in']/button[@class='Sign-in rx-btn mb0']")).click();

    if((driver.findElement(By.xpath(".//*[@id='globalMessages']/div"))).isDisplayed())
    {
        System.out.println("Login Failed");
        String Error=driver.findElement(By.xpath(".//*[@id='globalMessages']/div")).getText();
        System.out.println("The Error mesaage is :"+Error);
        System.out.println("***********************************************************************************************************");
    }
    else
    {
        System.out.println("Login Sucessfull");
        System.out.println("***********************************");
        driver.findElement(By.xpath(".//*[@id='content-inner']/div[1]/div/div[2]/div[4]/div/div/ul/li[9]/a")).click();
    }
    driver.close();
}

如果显示IF条件,则打印失败,否则传递。它适用于失败条件,但是对于通过条件,它的checkig和显示无法找到元素

2 个答案:

答案 0 :(得分:1)

您需要使用下面的try catch块 -

try
{
    if((driver.findElement(By.xpath(".//*[@id='globalMessages']/div"))).isDisplayed())
    {
        System.out.println("Login Failed");
        String Error=driver.findElement(By.xpath(".//*[@id='globalMessages']/div")).getText();
        System.out.println("The Error mesaage is :"+Error);
        System.out.println("***********************************************************************************************************");
    }
}
catch (Exception e)
{
    System.out.println("Login Sucessfull");
    System.out.println("***********************************");
    driver.findElement(By.xpath(".//*[@id='content-inner']/div[1]/div/div[2]/div[4]/div/div/ul/li[9]/a")).click();
}

答案 1 :(得分:1)

等待元素可见:

如果

,请先尝试一下
WebDriverWait wait=new WebDriverWait(driver,30);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(".//*[@id='globalMessages']/div")));
//then your code.....