2016-02-19 121 views
-1

我在頁面中有大約50行。但是這些項目是按順序的。如何跳過selenium webdriver中不存在的定位符?

問題是當某人輸入並刪除了該表格行時。該ID不會出現在網頁..

例子:

User added 1st record: id 101 added. 
User added 2nd record: id 102 added 
User added 3rd record: id 103 added. 

如果用戶刪除第二個記錄,然後兩個記錄會在那裏的頁面上,但ID爲101,103

我我試圖寫,如果該ID是存在的,然後得到文本,否則離開在for循環。我得到的只有記錄,直到它找到,如果沒有發現該ID變得NoSuchElementException顯示。

請更正代碼。但我想解決方案,如果該ID不存在,跳過並運行其他部分。

for (int i = counterstart; i <= counterend; i++) { 
    if(driver.findElement(By.xpath("//*[@id='" + i + "']/a")).isDisplayed()){ 
     System.out.println(i+" is present"); 
     String Projects = driver.findElement(By.xpath("//*[@id='" + i + "']/a")).getText(); 
     System.out.println(Projects);   
    } else{ 
     System.out.println(i+" is NOT present"); 
    } 
} 

,我得到異常:

異常線程 「main」 org.openqa.selenium.NoSuchElementException:無法找到使用XPath == // * [@ ID ='7593元「] /一個(警告:服務器沒有提供任何堆棧跟蹤信息) 命令持續時間或超時:503毫秒

+0

如果您讓用戶編輯和刪除數據,您怎麼可能編寫穩定/確定性測試或做適當的斷言(而不是捕獲和忽略異常)? –

回答

0

嘗試此方法isPresent代替isDisplayed。

public boolean isPresent(WebElement e) { 
    boolean flag = true; 
    try { 
     e.isDisplayed(); 
     flag = true; 
    } 
    catch (Exception e) { 
     flag = false; 
    } 
    return flag; 
} 
+0

您將您的方法稱爲isPresent而不是isDisplayed,但您只需在try塊中調用isDisplayed()! –

0
How about this: 

     for (int i = counterstart; i <= counterend; i++) { 

      WebElement element; 

      try{ 
       element = driver.findElement(By.xpath("//*[@id='" + i + "']/a")); 
      }catch(NoSuchElementException n) 
      { 
       element = null; 
      } 

      if(element !=null){ 
       System.out.println(i+" is present"); 
       String Projects = driver.findElement(By.xpath("//*[@id='" + i + "']/a")).getText(); 
       System.out.println(Projects); 
      }else{ 
       System.out.println(i+" is NOT present"); 
      } 
     } 
0

找到所有你想從文字並用它來鑽到元素的所有家長,這樣你就不會得到的異常

假設HTML看起來像這

<div id="parent"> 
    <div id="11"> 
    <a>text</a> 
    </div> 
    <div id="12"> 
    <a>text</a> 
    </div> 
    <div id="13"> 
    <a>text</a> 
    </div> 
</div> 

你可以做到這一點

// get all the elements with id 
List<WebElement> ids = driver.findElements(By.cssSelector("#parent > div")); 

// get all the texts using the id elements 
for (WebElement id :ids) { 
    String projects = id.findElement(By.tagName("a")).getText(); 
    System.out.println(projects); 
} 
相關問題