简体   繁体   中英

list item li is not selecting from drop down through Selenium WebDriver

I need to select an item in the drop down box. This drop down box works as ul and li items.

Drop down is being recognized as span element and the list that displays when clicking the drop down button being recognized as ul and li items.

When the below code is used to select the item, error message says that the weblement is not visible on click.

The li elements innerHTML property correctly returns the status text but getText() method returns empty.

oStatusLi.isDisplayed() always returns false even when the drop down list box is opened.

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;
    }
}

Appreciate if any body can help me on this to select the list item on java code.

First and foremost: It is bad practice to store a WebElement in memory, as it can lead to StaleElementExceptions. It may work now, but down the road, you will end up scratching your head at the odd failures that occur because of this.

Secondly, you can handle selection of your element by using a single selector, rather than loading all of the < li > elements into memory and iterating over them.

//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();

You may just end up having to execute the JavaScript function click on the element as well, depending on if scrollIntoView worked.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM