2015-05-20 127 views
1

我需要在下拉框中選擇一個項目。此下拉框可用作ulli項目。列表項li不是從下拉菜單中選擇Selenium WebDriver

下拉列表已被認可爲span元素並單擊下拉按鈕時,被識別爲UL項顯示的列表。

當使用下面的代碼選擇該項目時,錯誤消息表示在點擊時不顯示該weblement。

元素的innerHTML屬性正確返回狀態的文本,但getText()方法返回空。

oStatusLi.isDisplayed()即使在打開下拉列表框時也總是返回false。

WebElement statusUl = driver.findElement(By.xpath("//*[@id='ddlCreateStatus-" + strProjId + "_listbox']")); 
statusUl.click(); 
Thread.sleep(3000); 

List<WebElement> oStatusLis = statusUl.findElements(By.tagName("li")); 

for(WebElement oStatusLi: oStatusLis){ 

    if(oStatusLi.getAttribute("innerHTML")=="Paused") 
    { 

    oStatusLi.click(); 
    break; 
    } 
} 

感謝任何機構可以幫助我選擇java代碼上的列表項。

+0

你能提供'html'嗎? – Saifur

+1

在當前代碼中oStatusLi.click();永遠不會執行。對於按值進行字符串比較,您需要使用oStatusLi.getAttribute(「innerHTML」)。equals(「Paused」)而不是==。 – skandigraun

回答

0

首先也是最重要的:將WebElement存儲在內存中是不好的做法,因爲它可能會導致StaleElementExceptions。它現在可能會起作用,但是在這之後,你會因爲這個原因而發生奇怪的失敗而頭疼。其次,您可以使用單個選擇器來處理元素的選擇,而不是將所有的元素加載到內存中並遍歷它們。

//Store the selectors rather than the elements themselves to prevent receiving a StaleElementException 
String comboSelector = "//*[@id='ddlCreateStatus-" + strProjId + "_listbox']"; 
String selectionSelector = comboSelector + "//li[contains(.,'Paused')]"; 

//Click your combo box. I would suggest using a WebDriverWait or FluentWait rather than a hard-coded Thread.sleep here 
driver.findElement(By.xpath(comboSelector)).click(); 
Thread.sleep(3000); 

//Find the element to verify it is in the DOM 
driver.findElement(By.xpath(selectionSelector));  

//Execute JavaScript function scrollIntoView on the element to verify that it is visible before clicking on it. 
JavaScriptExecutor jsExec = (JavaScriptExecutor)driver; 
jsExec.executeScript("arguments[0].scrollIntoView();", driver.findElement(By.xpath(selectionSelector))); 
driver.findElement(By.xpath(selectionSelector)).click(); 

你可能只是最終不得不執行元件上的JavaScript函數點擊爲好,這取決於是否scrollIntoView工作。

相關問題