2017-03-16 105 views
1

我正在爲以下代碼編寫selenium腳本。動態查找使用硒xpath的以前的同級元素

<div id="abc" class="ui-selectmanycheckbox ui-widget hpsapf-chechkbox"> 
    <div class="ui-chkbox ui-widget"> 
     <div class="ui-helper-hidden-accessible"> 
      <input id="abc:0" name="abc" type="checkbox" value="0" checked="checked"> 
     </div> 
     <div class="ui-chkbox-box ui-widget ui-corner-all ui-state-default ui-state-active"> 
      <span class="ui-chkbox-icon ui-icon ui-icon-check ui-c"></span> 
     </div> 
    </div> 
    <span class="hpsapf-radio-label"> 
     <label for="abc:0">Herr</label> 
    </span> 
    <div class="ui-chkbox ui-widget"> 
     <div class="ui-helper-hidden-accessible"> 
      <input id="abc:1" name="abc" type="checkbox" value="1"> 
     </div> 
     <div class="ui-chkbox-box ui-widget ui-corner-all ui-state-default"> 
      <span class="ui-chkbox-icon ui-icon ui-icon-blank ui-c"></span> 
     </div> 
    </div> 
    <span class="hpsapf-radio-label"> 
     <label for="abc:1">Frau</label> 
    </span> 
</div> 

這些複選框如下所示。複選框的數量根據數據庫值進行更改。

enter image description here

在我的代碼我首先檢查了「已婚的女性」複選框是否被選中與否。所以我試着下面的代碼片段。

WebElement mainElement= driver.findElement(By.id("abc")); 
WebElement label=mainElement.findElement(By.xpath(".//label[contains(@for,'abc')][text() = 'Frau']")); 
WebElement parent = label.findElement(By.xpath("..")); 
WebElement div = parent.findElement(By.xpath("preceding-sibling::::div")); 
WebElement checkBox = div.findElement(By.className("ui-chkbox-box")); 
String css = checkBox.getAttribute("class"); 
if(css.contains("ui-state-active")) { 
    return "checked"; 
} 
else 
{ 
    return "unchecked"; 
} 

但是,當我試圖執行此腳本。 WebElement div = parent.findElement(By.xpath("preceding-sibling::::div"));給了我第一個div標籤,而不是前一個。我想要一個兄弟姐妹。

回答

2

使用::和索引,不::::

WebElement div = parent.findElement(By.xpath("preceding-sibling::div[1]")); 
+0

但如果我有3個的複選框,並要檢查3嗎?這是否工作 –

+0

@CharveeShah'div [1]'中的索引將引導你到你想要的元素。 – Guy