单击 Java selenium 中 Web 元素列表的特定元素

Click in a specific element of list of web elements in Java selenium

我在 java 中使用黄瓜和硒自动化网页,我有这个 xpath

      .//*[@id='chosen_motivos_investimentos_chosen']/div[1]/ul[1]

在 ul[1] 里面我有一堆 li,在这种情况下我有 html:

的这一部分
<ul class="chosen-results">
<li class="active-result" style="" data-option-array-index="1">LA - Media Buying Fees ‐ Traditional</li>
<li class="active-result" style="" data-option-array-index="2">LL - Marketing Development</li>
<li class="active-result" style="" data-option-array-index="3">LQ - Media Buying Fees ‐ Digital</li>
<li class="active-result" style="" data-option-array-index="4">LU - Media Costs ‐ Traditional</li>
<li class="active-result" style="" data-option-array-index="5">LV - Advertising Production Costs ‐ Traditional</li>
</ul>

我想点击特定的 li 到 select,这个特定的是通过参数 (String despesa) 给出的,我试过这个:

    Thread.sleep(2000);
    wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(".//*[@id='chosen_motivos_investimentos_chosen']/a"))).click();
    List<WebElement> dropDespesa = driver.findElements(By.xpath(".//*[@id='chosen_motivos_investimentos_chosen']/div[1]/ul[1]"));
    i = dropDespesa.iterator();
    while(i.hasNext()){
        WebElement row = i.next();
        if(row.getText().equalsIgnoreCase(despesa)){
            System.out.println("Igual");
            row.click();
        }
        System.out.println(row.getText());
    }

但是 webdriver 永远不会进入 if,我已经调试并确保 despesa 实际上等于 row.getText()

您可以通过文字定位到想要的li并点击它:

// open up the dropdown
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(".//*[@id='cho‌​sen_motivos_investimentos_chosen']/a"))).click();

WebElement dropDespesa = driver.findElement(By.xpath(".//*[@id='chosen_motivos_investimentos_chosen']/div[1]/ul[1]"));

dropDespesa.findElement(By.xpath(".//li[. = '" + despesa + "']")).click();