使用Selenium和Java自动化基于jQuery的引导下拉列表



我正在尝试从引导下拉列表中列出所有元素,然后选择某个值。但是,它返回 0 个值。任何建议将不胜感激。

driver.findElement(By.id("imgSelectButton")).click();
Thread.sleep(3000);
List<WebElement> list = driver.findElements(By.xpath("//ul/li[@class='logoSelectOpt']//li"));
System.out.println(list.size());
for(int i=0; i<list.size(); i++){
System.out.println(list.get(i).getText());
if (list.get(i).getText().contains("History")){
list.get(i).click();
break;
}
}

多姆:

<div class="logoSelect" style="z-index:1; top:878px;">==$0
<ul>
<li class="logoSelectOpt" id="12" onmouseover="jQuery(QWE01Title.activate(this);" onmouseout="jQuery(QWE01Title.deactivate(this);" onmousedown="jQuery(QWE01Title.selectItem(this);" logoColor="#FFF">Facts</li>==0
<li class="logoSelectOpt" id="12" onmouseover="jQuery(QWE01Title.activate(this);" onmouseout="jQuery(QWE01Title.deactivate(this);" onmousedown="jQuery(QWE01Title.selectItem(this);" logoColor="#FFF">History</li>==0
<li class="logoSelectOpt" id="12" onmouseover="jQuery(QWE01Title.activate(this);" onmouseout="jQuery(QWE01Title.deactivate(this);" onmousedown="jQuery(QWE01Title.selectItem(this);" logoColor="#FFF">Opinions</li>==0
<li class="logoSelectOpt" id="12" onmouseover="jQuery(QWE01Title.activate(this);" onmouseout="jQuery(QWE01Title.deactivate(this);" onmousedown="jQuery(QWE01Title.selectItem(this);" logoColor="#FFF">Questions</li>==0
</ul>
</div>

这些元素是启用 jQuery 的元素,因此要找到这些元素,您必须诱导WebDriverWaitfor thevisibilityOfAllElementsLocatedBy(),您可以使用以下任一定位器策略:

  • 使用cssSelector

    driver.findElement(By.id("imgSelectButton")).click();
    List<WebElement> list = new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfAllElementsLocatedBy(By.cssSelector("div.logoSelect > ul li.logoSelectOpt")));
    System.out.println(list.size());
    for(int i=0; i<list.size(); i++){
    System.out.println(list.get(i).getText());
    if (list.get(i).getText().contains("History")){
    list.get(i).click();
    break;
    }
    }
    
  • 使用xpath

    driver.findElement(By.id("imgSelectButton")).click();
    List<WebElement> list = new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfAllElementsLocatedBy(By.xpath("//div[@class='logoSelect']/ul//li[@class='logoSelectOpt']")));
    System.out.println(list.size());
    for(int i=0; i<list.size(); i++){
    System.out.println(list.get(i).getText());
    if (list.get(i).getText().contains("History")){
    list.get(i).click();
    break;
    }
    }
    

最新更新