使用Java中的if / else处理警报

时间:2017-08-19 06:28:37

标签: java selenium webdriver

如何使用 if / else 命令处理提醒?如果出现警报,请执行接受/拒绝,否则继续进行。我尝试使用下面的代码,但(r == true)的错误表示不兼容的类型。

bool r = driver.findElement(By.xpath("//div[contains(text(),'javax.baja.sys.ActionInvokeException')]"));
if (r = true) {
    driver.switchTo().alert().accept();
} else {
    Actions click2 = new Actions(driver);
    WebElement dclick2 = driver.findElement(By.xpath(".//span[text()='Bluemix_As_Device']"));
    click2.moveToElement(dclick2).doubleClick().build().perform();
}

3 个答案:

答案 0 :(得分:1)

不兼容的类型是

的原因
driver.findElement 

将返回WebElement类型,而不是boolean(即java)。您可能希望将代码更改为:

try {
    WebElement r = driver.findElement(By.xpath("//div[contains(text(),'javax.baja.sys.ActionInvokeException')]"));
    driver.switchTo().alert().accept(); // this would be executed only if above element is found
} catch (NoSuchElementException ex) {
    // since the element was not found, I 'm still doing some stuff
    Actions click2 = new Actions(driver);
    WebElement dclick2 = driver.findElement(By.xpath(".//span[text()='Bluemix_As_Device']"));
    click2.moveToElement(dclick2).doubleClick().build().perform();
}

答案 1 :(得分:0)

由于r是布尔类型所以不需要写if(r == true)或if(r == false)你可以直接写if(r)和java将理解代码。

答案 2 :(得分:0)

driver.findElements will check the existence of the object and will return 1 if exist else zero.
So in your case though the alert exist or not, it will handle and based on size it will execute next step. Hope this helps in your case.

int r= driver.findElements(By.xpath("//div[contains(text(),'javax.baja.sys.ActionInvokeException')]")).size();
if(r!=0){
    driver.switchTo().alert().accept();
} else {
    Actions click2 = new Actions(driver);
    WebElement dclick2 = driver.findElement(By.xpath(".//span[text()='Bluemix_As_Device']"));
    click2.moveToElement(dclick2).doubleClick().build().perform();
}