【问题标题】:list item li is not selecting from drop down through Selenium WebDriver列表项 li 未通过 Selenium WebDriver 从下拉列表中进行选择
【发布时间】:2015-05-21 05:09:05
【问题描述】:

我需要在下拉框中选择一个项目。此下拉框可用作 ulli 项。

下拉被识别为 span 元素,当单击下拉按钮时显示的列表被识别为 ulli 项。

当使用下面的代码选择项目时,错误消息说 weblement 在点击时不可见。

li 元素的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代码上的列表项。

【问题讨论】:

  • 你能提供html吗?
  • 在当前代码中 oStatusLi.click();永远不会被执行。对于按值进行字符串比较,您需要使用 oStatusLi.getAttribute("innerHTML").equals("Paused") 而不是 ==。

标签: java selenium selenium-webdriver webdriver


【解决方案1】:

首先:将 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 是否有效。

  • 【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多