[英]prevent Selenium WebDriver to exit after catching an exception
我正在使用Selenium Web Driver
填寫一個簡單的表格:
private WebDriver driver = new FirefoxDriver();
和功能:
public boolean fillDetailsInWeb(JsonElement data,String url){
System.out.println("fill in-"+url);
boolean result = false;
try{
driver.navigate().to(url);
}catch(Exception e){
System.out.println("Error in driver " + e.getMessage().toString());
return result;
}
//web elements
try{
WebElement name_to_input = driver.findElement(By.id("ID1"));
WebElement email_to_input = driver.findElement(By.id("id2"));
WebElement message_to_input = driver.findElement(By.id("ID3"));
}catch(NoSuchElementException MSEE){
MSEE.printStackTrace();
}
result = true;
return result;
}
我希望該過程在捕獲NoSuchElementException
之后繼續進行,並使程序轉到下一個站點。 正確的做法是什么?
循環播放不會繼續進行下一步。
嘗試首先確定不存在哪個元素,或者在每個步驟中進行驗證,例如:
try{
WebElement name_to_input = driver.findElement(By.id("ID1"));
}catch(Exception MSEE){
MSEE.printStackTrace();
}
try{
WebElement name_to_input = driver.findElement(By.id("ID2"));
}catch(Exception MSEE){
MSEE.printStackTrace();
}
要么
String[] id = {"id1","id2"}
for(int c=0;c<2;c++)
try{
WebElement name_to_input = driver.findElement(By.id(id[c]));
}catch(Exception MSEE){
MSEE.printStackTrace();
}
我僅將NoSuchElementException更改為Exception,以便該元素存在但不可見。 硒仍移至下一步。
我只是新手,但希望能有所幫助。
如標題所述,即使在發生意外異常的情況下仍要繼續執行,則需要同時使用The Finally Block
和“ Try...Catch...
塊。
從這個鏈接:
try塊退出時,finally塊始終執行。 這樣可以確保即使發生意外異常,也可以執行finally塊。 但是,最后,它不僅對異常處理有用,它還使程序員避免因返回,繼續或中斷而意外地跳過清理代碼。 即使在沒有例外的情況下,將清除代碼放在finally塊中始終是一個好習慣。
因此,使用Final的Try Catch塊將是:
...
try{
driver.navigate().to(url);
}catch(Exception e){
System.out.println("Error in driver " + e.getMessage().toString());
return result;
}
//web elements
try{
WebElement name_to_input = driver.findElement(By.id("ID1"));
WebElement email_to_input = driver.findElement(By.id("id2"));
WebElement message_to_input = driver.findElement(By.id("ID3"));
}catch(NoSuchElementException MSEE){
MSEE.printStackTrace();
} finally {
return result;
}
...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.