首页 > 解决方案 > C# Selenium 如何在特定文本旁边找到下拉列表?

问题描述

我正在尝试测试包含多个下拉列表的页面,这些下拉列表在每次刷新时在页面中具有动态 ID 和动态位置。

在此处输入图像描述

例如,我想首先找到与标签 5 对应的下拉列表并选择特定值,所以我想通过它旁边的标签找到下拉列表。

我试过这个:

driver.FindElement(By.XPath("//span[text()='Label 5']/following::div[@class='select custom-select custom-select m-l-1']"));

但我收到“无法定位”错误。

编辑:添加下拉列表 HTML 代码:

<tr class="r0">
    <td class="text">
        <p>Label 5
            <br>
        </p>
    </td>
    <td class="control">
        <label class="accesshide" for="menuq6803:2_sub0">Answer 1</label>
        <select class="select custom-select custom-select m-l-1" id="menuq6803:2_sub0" name="q6803:2_sub0">
            <option value="0">Choose...</option>
            <option value="1">This is answer 1</option>
            <option selected="selected" value="2">This is answer 2</option>
        </select>
    </td>
</tr>

标签: c#selenium-webdriver

解决方案


这里有几个应该可以工作的 XPath

//p[contains(text(),'Label 5')]/following::select

或者

//tr[.//p[contains(text(),'Label 5')]]/td/select

第二个更安全,因为它要求 Label 和 SELECT 都在同一个 TR 下。


推荐阅读