簡體   English   中英

在Java中使用if / else處理警報

[英]Handling alerts using if/else in Java

如何使用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();
}

不兼容的類型是因為

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

由於r是布爾類型,因此無需編寫if(r == true)或if(r == false),您可以直接編寫if(r),而Java會理解代碼。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM