2017-07-21 49 views
2

我有一個菜單,顯示鼠標懸停列表,我想點擊註銷。 我寫了一些代碼,但無法獲得所需的結果。如何選擇裏面的div-> ul-> li中的元素

這裏是我的Java代碼:

public void Logout() throws Exception { 
     WebElement profileDropdown = driver.findElement(By.className("profile-dropdown")); 
     //profileDropdown.click(); 
     //profileDropdown.findElement(By.id("lnkLogout")).click(); 
     //Select oSelect = new Select(driver.findElement(By.className("profile-dropdown"))); 

     //oSelect.selectByVisibleText("Log Out"); 
     //List<WebElement> li = profileDropdown.findElements(By.id("lnkLogout")); 
     //li.get(0).click();//If there are only two such element, here 1 is index of 2nd element in list returned. 

     List<WebElement> elems = driver.findElements(By.cssSelector("ul>li>a")); 
     elems.get(5).click(); 
     //profileDropdown.findElement(By.xpath("(//a[contains(text(),'Log Out')])[2]")).click(); 

    } 

我試過很多東西,你可以看到,被註釋掉的代碼行。沒有任何作品適合我。

這裏是我的HTML代碼,其中我對

<div style="display: none;" class="profile-dropdown"> 
       <ul> 
        <li><a href="https://consumers.keenu.pk/index.php/profile/">My Profile <!--<label id="lblProfilePercentage">0</label>--></a></li> 
        <li><a href="https://consumers.keenu.pk/index.php/transactionhist/">Transaction History</a></li> 
        <li><a href="https://consumers.keenu.pk/index.php/customer-care/helpline">Helpline</a></li> 
        <li><a href="https://consumers.keenu.pk/index.php/pin-pass/">PIN &amp; Password</a></li> 
        <li><a href="https://consumers.keenu.pk/index.php/settings/">Favorites</a></li> 
        <li><a href="#" id="lnkLogout" style="cursor:pointer">Log Out</a></li> 
       </ul> 
      </div> 

它能夠找到「配置文件的下拉菜單」元素,但隨後引發異常,無法找到列表元素進行自動化。

請幫忙。

回答

1

如果你說你的菜單項出現,當你在菜單上做mousehoever然後點擊它是行不通的。您需要:

1.mouse懸停即使在菜單第一

2.need等到註銷菜單項(鏈接)是其可見

3.click。

Actions action = new Actions(driver); 
action.moveToElement(profileDropdown).build().perform(); 
WebDriverWait wait = new WebDriverWait(driver, 30); 
WebElement logoutLink = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("lnkLogout"))); 
logoutLink.click(); 
+0

預期條件失敗:等待By.xpath找到的元素的可見性:(// a [contains(text(),'Log Out')])[2](試過30秒)與500 MILLISECONDS間隔) – Asad

+0

你可以嘗試與ID,我已經更新了答案,也不關閉瀏覽器,並檢查行爲,你能看到菜單項? –

+0

同樣的錯誤,無法看到菜單項。 – Asad

-1

我會推薦你​​使用jquery。這段代碼只有在包含jquery google cdn的頭文件中才有效。 在身體標記後嘗試此代碼。

<script> 
function whatever(){ 
$(".profile-dropdown > ul > li > #lnkLogout").click(); 
} 


</script> 
相關問題