gpt4 book ai didi

java - 如何使用 Selenium WebDriver 从下拉框中选择一个项目?

转载 作者:行者123 更新时间:2023-12-01 15:23:19 26 4
gpt4 key购买 nike

我正在尝试使用java代码自动化测试用例。我使用selenium服务器库进行相同的操作。现在,当我到达某个页面时,我会得到一个包含一定数量元素的下拉框。下拉框称为“流派”。现在我想要做的是单击我想要展开的下拉框,以便下一步我可以单击特定的项目,例如。摇滚/金属/流行音乐等。以上所有内容我都在尝试自动化,但每次我这样做时都会抛出相同的异常:

Exception in thread "main" org.openqa.selenium.NoSuchElementException: Unable to locate element: {"method":"xpath","selector":"//*[@id='Genre']"}

我已经尝试了By(即By.xpath、By.name、By.id等)可用的各种方法,但无济于事。因此,我复制粘贴与“流派”框相关的信息供您引用。请指导我使用哪种方法才能成功实现我刚才描述的目标。

当我突出显示“流派”时,查看选择源:

<td id="genre" width="50%">
Genre <br><select name="Genre" id="Genre" class="input_boxbbb" onchange="subgener(this.value)"><option value="0000">All</option><option value="26">AIRTEL JINGLE</option><option value="19">ARTISTS</option><option value="27">BATTERY</option><option value="25">BOLLYWOOD</option><option value="28">

最佳答案

好的,Pavel 建议的代码是正确的并且应该可以工作。

我对此只有一条评论。您可以只使用以下选项之一,而不是手动迭代所有选项:

genres.selectByIndex(int index)
genres.selectByValue(String value)
genres.selectByVisibleText(String text)

问题出在 HTML 上,请注意您有 2 个具有相同 id 但大小写不同的元素。

<td id="genre" width="50%">
<select name="Genre" id="Genre">

这可能会导致窗帘浏览器出现问题,并且通常是不好的做法。

如果你控制 HTML,我建议更改 <td> 的 id元素到其他东西并使用上面的代码。

如果您不是编写 HTML 的人,请尝试使用

Select genre = new Select(driver.findElementBy(By.name("Genre"))) [Notice the Case sensetivity];

如果这不起作用,请尝试检查所有 <select>页面中的元素并使用它来选择您需要的元素:

List<WebElement> selects = driver.findElementsBy(By.tagName("select"));
for (WebElement select : selects) {
System.out.println(select)
}

希望对你有帮助

关于java - 如何使用 Selenium WebDriver 从下拉框中选择一个项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10546974/

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