gpt4 book ai didi

java - Selenium - 使用通配符从下拉列表中选择一个选项?

转载 作者:太空宇宙 更新时间:2023-11-04 14:30:44 24 4
gpt4 key购买 nike

从 Selenium 的下拉列表中选择选项时是否可以使用通配符?我正在开发一个网络应用程序,将文件上传到服务器。上传文件后,我可以通过从下拉列表中选择该文件来执行操作。但是,下拉列表显示文件以及文件的大小,因此在查看选项时它将显示“文件名 - 0.5 GB”。我无法使用 selectByValue,因为 value 属性是随机分配的,并且我无法使用 selectByIndex,因为选项的顺序可能会根据显示的文件数量而变化。

我能想到的最好的办法就是这样(Java 代码):

Select sel = = new Select(dropdown);
List<WebElement> list = sel.getOptions();
for (WebElement option : list) {
if (option.getText().contains(data.getImageName())) {
sel.selectByVisibleText(option.getAttribute("value"));
break;
}
}

但我想当我不知道要显示的确切文本时,必须有更好的方法从下拉列表中选择选项。有吗?

最佳答案

根据Select class implementation ,只有 selectByVisibleText() 相关方法,但它relies on the full option text ,不是部分的:

List<WebElement> options =
element.findElements(By.xpath(".//option[normalize-space(.) = " + escapeQuotes(text) + "]"));

如您所见,它在 xpath 表达式中使用 = 匹配。

解决方案是使用 xpath 的 contains()“手动”查找选项并调用 setSelected() :

Select sel = = new Select(dropdown);
WebElement option = driver.findElement(By.xpath('//path/to/select//option[contains(., "Partial text")]'));
sel.setSelected(option);

关于java - Selenium - 使用通配符从下拉列表中选择一个选项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26184039/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com