【问题标题】:How to xpath selected text in the dropdown如何xpath在下拉列表中选择文本
【发布时间】:2018-11-11 06:10:27
【问题描述】:
**HTML Code**
  <div class="form-group">
        <label class="control-label col-md-4 col-sm-4" for="type-select">Category<span style="color:red">*</span></label>
        <div class="col-md-8 col-sm-8">
            <select defaultattr="4" class="form-control input-style mandatory" data-val="true" data-val-number="The field CategoryID must be a number." id="CategoryID" name="CategoryID"><option value="">--Select--</option>
<option value="1">Architectural Firm</option>
<option value="2">Interior Design Firm</option>
<option value="3">General Contractor</option>
<option selected="selected" value="4">2tec2 Sales Network</option>
<option value="5">Cleaning Company</option>
<option value="6">Commercial end user</option>
<option value="7">Distribution company</option>
<option value="8">Hotel Company</option>
</select>

我希望 xpath 获取选定的值(这里是上面代码中的第 4 个选项)。

【问题讨论】:

  • 显示下拉菜单的html文本代码
  • 您可以使用 Select Class 来获取 Drop-Down 值
  • "
  • @Ankur Singh - 我如何在 xpath 中使用 SelectClass
  • @Bhuvana 通过在问题中添加 HTML 来更新您的问题,提供详细信息。

标签: java selenium selenium-webdriver automation


【解决方案1】:

您希望 xpath 获取下拉列表的选定选项吗?

试试这个 xpath://select[@id='CategoryID']//option[@selected='selected']

您使用 GetText() 获取所选文本的文本

String text = driver.findElement(By.xpath(...)).getText();

【讨论】:

  • 这很有帮助。但这并不是我真正需要的。上面我已经发布了一个下拉字段的 html 代码。有类似的 5 个下拉列表,我需要在每个下拉列表中获取选定的文本并将其存储在一个数组中
【解决方案2】:

除了 Shn 的回答和您对此的评论。 如果您需要从 5 个类似的下拉列表中获取值,为什么不为每个下拉列表运行给定的 xpath 语句 5 次(通过更改 xpath 中的 id)并将它们全部保存在一个数组中

String textA = driver.findElement(By.xpath(...)).getText();
String textB = driver.findElement(By.xpath(...)).getText();
String textC = driver.findElement(By.xpath(...)).getText();
String textD = driver.findElement(By.xpath(...)).getText();
String textE = driver.findElement(By.xpath(...)).getText();

String array[] = new String[] { textA, textB, textC, textD, textE };

您也可以为此使用循环。

【讨论】:

    猜你喜欢
    • 2022-11-12
    • 1970-01-01
    • 1970-01-01
    • 2019-09-06
    • 2019-02-27
    • 2015-11-14
    • 2020-01-02
    • 1970-01-01
    • 2020-05-06
    相关资源
    最近更新 更多