无法从下拉选项中获取文本

wvmv3b1j  于 2021-07-03  发布在  Java
关注(0)|答案(2)|浏览(299)
driver.findElement(By.xpath("//*[@id=\"_desktop_currency_selector\"]/div")).click();
List<WebElement> list = driver.findElements(By.xpath("//*[@id=\"_desktop_currency_selector\"]/div/ul//li"));

System.out.println(list.size());

for (int i=0; i<list.size(); i++){
    System.out.println(list.get(i).getText());
}

输出:

欧元€
我需要从下拉列表中的项目中获取文本,我的代码可以找到所有li元素并打印它们的数量,但是当我尝试从它们中打印可见文本时,我只从第一个选项中获取文本:(
如果你能给我一个提示,我将非常感激。。。
部分页面源:

<div id="_desktop_currency_selector">
  <div class="currency-selector dropdown js-dropdown">
    <span>Currency:</span>
    <span class="expand-more _gray-darker hidden-sm-down" data-toggle="dropdown">UAH ₴</span>
    <a data-target="#" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" class="hidden-sm-down">
      <i class="material-icons expand-more">&#xE5C5;</i>
    </a>
    <ul class="dropdown-menu hidden-sm-down" aria-labelledby="dLabel">
              <li >
          <a title="European EURO" rel="nofollow" href="http://wasd.com.ua/ru/search?order=product.price.desc&amp;s=dress&amp;SubmitCurrency=1&amp;id_currency=2" class="dropdown-item">EUR €</a>
        </li>
              <li  class="current" >
          <a title="Ukrainian UAH" rel="nofollow" href="http://wasd.com.ua/ru/search?order=product.price.desc&amp;s=dress&amp;SubmitCurrency=1&amp;id_currency=1" class="dropdown-item">UAH ₴</a>
        </li>
              <li >
          <a title="Dollar USA" rel="nofollow" href="http://wasd.com.ua/ru/search?order=product.price.desc&amp;s=dress&amp;SubmitCurrency=1&amp;id_currency=3" class="dropdown-item">USD $</a>
        </li>
          </ul>
    <select class="link hidden-md-up">
              <option value="http://wasd.com.ua/ru/search?order=product.price.desc&amp;s=dress&amp;SubmitCurrency=1&amp;id_currency=2">EUR €</option>
              <option value="http://wasd.com.ua/ru/search?order=product.price.desc&amp;s=dress&amp;SubmitCurrency=1&amp;id_currency=1" selected="selected">UAH ₴</option>
              <option value="http://wasd.com.ua/ru/search?order=product.price.desc&amp;s=dress&amp;SubmitCurrency=1&amp;id_currency=3">USD $</option>
          </select>
  </div>
nfeuvbwi

nfeuvbwi1#

我加了一句 a 在结尾贴上标签,看起来很管用。

List<WebElement> list = driver.findElements(By.xpath("//*[@id=\"_desktop_currency_selector\"]/div/ul/li/a"));

如果你只是想打印 text 内部 <option> 使用以下标记:

List<WebElement> list = driver.findElements(By.xpath("//*[@id=\"_desktop_currency_selector\"]/div/select/option"));

两者产生相同的结果。
输出:

3
EUR €
UAH ₴
USD $
tcomlyy6

tcomlyy62#

// preprare emtpy list
    List<String> texts = new ArrayList<String>();

    // get the dropdown element
    WebElement dropDown = driver.findElement(By.className("link hidden-md-up"));

    // get dropdown options
    List<WebElement> options = dropDown.findElements(By.tagName("option"));

    // collect texts
    for (WebElement option: options) {
        texts.add(option.getText());
    }

相关问题