【问题标题】:Selenium - How do I get the the list of options of a drop down list using java?Selenium - 如何使用 java 获取下拉列表的选项列表?
【发布时间】:2020-08-02 08:52:06
【问题描述】:

我有以下代码:

<span class="dropDown">Choose</span>
<div class="dropdownQuestions active" style="display: block; max-height: 310px;">
<span data-index="0" data-value="1" onclick="gt.setQuestion(this, true);">Warrior</span>
<span data-index="1" data-value="2" onclick="gt.setQuestion(this, true);">Mage</span>
<span data-index="2" data-value="3" onclick="gt.setQuestion(this, true);">Sorcerer</span>

如果可能的话,我想要的是下拉列表的列表,所以在我可以使用其中一个单击之后,我进行了很多搜索,但找不到任何对我有帮助的答案。

其他选项是使用数据索引或数据值字符串单击。 我想要的最后一个选项是点击字符串“Warrior”、“Mage”或“Sorcerer”,但如果没有其他方法,我会很高兴的。

谢谢!

【问题讨论】:

    标签: java selenium selenium-webdriver


    【解决方案1】:

    单击下拉菜单后,您可以在列表中获取所有下拉选项,然后根据需要使用它们(循环并选择具有特定条件的所需选项或通过索引获取选项)。

      List<WebElement> options= driver.findElements(By.xpath("//span[@class='dropDown']/div/span"));
      options.get(1).click(); // here 1 is the index value of the option to select or you can use loop if looking for some specific condition
    

    对于您在评论中分享的图片链接,请尝试以下 cssSelector:

    List<WebElement> option= driver.findElements(By.cssSelector("div.questionDropdownOptions.activeSelectMenu span"));
                    option.get(1).click();
        }
    

    注意:请在您的代码中导入以下包:

    import java.util.List;
    import org.openqa.selenium.By;
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.WebElement;
    

    【讨论】:

    • 感谢您的回答,但我得到“InvalidSelectorException”当我单击时会出现下拉菜单,div 类是其中包含选择的类(跨度)。我刚开始使用 selenium,所以不确定...我检查了代码并复制了 xpath 并将其添加到您的代码示例中...我有这个图像作为示例:ibb.co/1XrdRRf 这就是我想要的,里面的 coiches 列表div,供我以后随意使用。正如我所说,我尝试将 xpath/full xpath 从该 div 复制到您的示例。但没有运气感谢您的宝贵时间!
    • @TiagoMachado InvalidSelectorException 发生在代码中存在语法错误时。因为我不在我的电脑上,所以我通过电话回复。我会检查并在一段时间内回复您。
    • @TiagoMachado ,我已根据您的评论更新了我的答案。请检查它是否解决了您的问题。
    • 哇!我不知道该怎么感谢你!现在完美运行!!!!谢谢! ^_^
    【解决方案2】:

    我认为您要寻找的所有内容都已在此处得到解答:

    ->How to select a dropdown value in Selenium WebDriver using Java

    如果你想遍历它,这可能会有所帮助

    ->How to count the number of options in a select drop down box in Selenium WebDriver using Java?

    更具体地说,在第一个链接中,您可以看到您可以使用字符串参数单击下拉选项,也可以使用索引。

    我知道您可能正在寻找特定代码,但遗憾的是,我不在计算机上,但我很确定这个答案是您的问题。

    祝你的代码好运:)

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-08-21
    • 1970-01-01
    • 1970-01-01
    • 2021-01-14
    • 2020-11-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多