2014-09-29 72 views
-2

HTML代碼如何找到TD元素存在或不 - 硒的webdriver用java

<table class="adminlist" width="100%" cellspacing="0" cellpadding="0" border="0"> 
<tbody> 
<tr data-bind="if: RowCounts>0, attr: {StatusId: Id, DescName:Name}" statusid="2" descname="Abandoned"></tr> 
<tr data-bind="if: RowCounts>0, attr: {StatusId: Id, DescName:Name}" statusid="1" descname="Active"> 
<td style="width: 5%;"> 
<input type="checkbox" data-bind="attr: { accesskey: Id }" accesskey="1"> 
</td> 
<td class="country"> 
<span data-bind="text:Name">Active</span> 
(
<span data-bind="text:RowCounts">20</span> 
) 
</td> 
</tr> 

,我們怎樣才能找到「TD」元素存在或不與上表中,根據上述第一行不要有一個TD元素但第二行其具有T​​D元素

Java代碼

Hashtable<String, Integer> renewalStatus = new Hashtable<String, Integer>(); 
     List<WebElement> activeAssetStatus = driver.findElements(By 
       .xpath("//*[@id='divPatPortfolioStatusCount']/table/tbody/tr")); 

     for (int i = 1; i <= activeAssetStatus.size(); i++) { 
      List<WebElement> statusValue = activeAssetStatus.get(i) 
        .findElements(By.tagName("td")); 

      if (statusValue.size() > 0) { 
       WebElement al = driver 
         .findElement(By 
           .xpath("//*[@id='divPatPortfolioStatusCount']/table/tbody/tr[" 
             + i + "]/td[2]")); 

       String mainText = al.getText(); 
       final Pattern p = Pattern.compile("(.*?)\\s*\\((.*?)\\)"); 
       final Matcher m = p.matcher(mainText); 
       m.find(); 
       String name = m.group(1); 
       String count = m.group(2); 
       renewalStatus.put(name, Integer.parseInt(count)); 
      } 
     } 
} 

上面的代碼不能夠收集和TD值存儲在哈希表 其促領袖「NoSuchElementException異常」 因爲如果條件裏面i值1,因此其產生這種例外,我怎麼能收取相應的行與TD值

回答

0
List <WebElement> allTrElements = driver.findElements(By.xpath("//table[@class='adminlist']/tbody/tr")); 

for(int i= 0;i<allTrElements.size();i++){ 
    List<WebElement> allTdElements = allTrElements.get(i).findElements(By.tagName("td")); 
    if(allTdElements.size() > 0){ 
     // if confirms <tr> contains <td> 
    } 
} 
+0

@shekhar請裏面找到我的Java代碼我值的循環變成1 – Prabu 2014-09-29 10:27:55

0
WebDriver mainDriver = new ChromeDriver(); 

//get the table element 
WebElement eleTable = mainDriver.findElement(By.tagName("table"); 

//get the list of row elements of table 
List<WebElement>tableRowList = eleTable.findElements(By.tagName("tr")); 

for(int i = 0 ; i < tableRowList.size(); i++) { 
    //take individual rows 
    WebElement rowElement = tableRowList.get(i); 

    //get the list of td elements 
    List<WebElement> dataElement = rowElement.findElements(By.tagName("td")); 

    if(dataElement.size() > 0) { 
     //if size > 0, there are td elements in it. 
    } 
} 

+0

請找到我的java代碼 – Prabu 2014-09-29 10:35:32

+0

你能告訴我你想從td元素中獲取什麼嗎? – Shastry 2014-09-29 11:26:50

+0

:在該td(Active,20)內的span值,刮掉該表中的所有行查找並收集所有td值 – Prabu 2014-09-29 11:37:26