Java Selenium - 按 ul li 值文本从列表中选择项目

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38212644/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 20:05:20  来源:igfitidea点击:

Selenium - Select Item From List By The ul li Value Text

javaselenium-webdriver

提问by Dustin N.

I've got the following HTML

我有以下 HTML

<div id="colLeft_OrderGroups" class="GroupList GroupList_Left">
            <div class="SelectList" style="height:516px;">
                <div class="DialogSubtitle">Available groups</div>
                <ul class="ui-selectable" id="grdAvailableGroups" style="width:100%; margin-right:2px">
                <li value="10929">AppraisersGroupTest</li>
                </ul>
            </div>
        </div>

How do I select the option based off the "AppraisersGroupTest" text?

如何根据“AppraisersGroupTest”文本选择选项?

There will be multiple values in the list soon, so I need to be able to specify the text.

列表中很快就会有多个值,所以我需要能够指定文本。

I have tried the answer in this post, but I'm getting syntax errors I cannot resolve.

我已经尝试了这篇文章中的答案,但我遇到了无法解决的语法错误。

采纳答案by JeffC

Looking at your HTML, I'm going to assume that the valueof the desired LIis going to always be "10929" for your desired "AppraisersGroupTest." With that info, you can use the code below.

查看您的 HTML,我将假设value所需的LI“AppraisersGroupTest”始终为“10929”。有了这些信息,您就可以使用下面的代码。

String value = "10929";
WebElement dropdown = driver.findElement(By.id("grdAvailableGroups"));
dropdown.click(); // assuming you have to click the "dropdown" to open it
dropdown.findElement(By.cssSelector("li[value=" + value + "]")).click();

If it turns out that is not a good assumption, you can use the code below to search for the desired text and click the element.

如果事实证明这不是一个好的假设,您可以使用下面的代码搜索所需的文本并单击该元素。

String searchText = "AppraisersGroupTest";
WebElement dropdown = driver.findElement(By.id("grdAvailableGroups"));
dropdown.click(); // assuming you have to click the "dropdown" to open it
List<WebElement> options = dropdown.findElements(By.tagName("li"));
for (WebElement option : options)
{
    if (option.getText().equals(searchText))
    {
        option.click(); // click the desired option
        break;
    }
}

回答by Saurabh Gaur

You can achieve this using one liner xPathas below :-

您可以使用一个衬垫来实现这一点xPath,如下所示:-

String text = "AppraisersGroupTest";
WebElement el = driver.findElement(By.xpath("//div[@id = 'colLeft_OrderGroups']/descendant::li[text() = '" + text + "']"));
el.click();

Hope it will help you...:)

希望能帮到你...:)