如何使用Selenium WebDriver选择组合框值,其中它是具有组合框角色的div



我的HTML代码有一个div标记,其作用是combobox,即

<div role="combobox">...</div>

我正试图通过java的selenium驱动程序从组合框中选择一个项目。

我尝试使用此处推荐的"Select"类:如何使用Java 在Selenium WebDriver中选择下拉值

但由于它是一个div,我收到一个错误,说

"出乎意料的TagNameException:元素本应被选择,但却是div"

我认为这是因为div role="combobox"。

有什么办法解决这个问题吗?

因为没有

select html tag

在你的html代码中,

"Select" class will not work here.

所以你可以用两种方式(因为你没有给你详细的html代码)

第一道工序:

第一步:点击组合框。

第二步:点击组合框后,组合框选项将显示其链接文本或id或其他定位器。

为此,请使用以下代码:

driver.findElement(By.id("search_key.combobox")).click();//click on that combo

driver.findElement(By.linkText("ur combo option link text"));//click on ur desired combo option
or
driver.findElement(By.cssSelector("ur combo option's css path"));//u can use any other locator what is shown in ur html code after clicking on combo box

但在点击组合框后,如果组合选项在检查部分没有显示任何定位器,则使用以下代码:

driver.findElement(By.id("search_key.combobox")).click();//click on that combo
for(int i = 0; i <= position; i++){
    Actions actions = new Actions(driver);
    actions.sendKeys(Keys.DOWN).build().perform();//press down arrow key
    Actions actions = new Actions(driver);
    actions.sendKeys(Keys.ENTER).build().perform();//press enter
}
//here "position" is , ur desired combo box option position,
//for ex. u want to choose 3rd option,so ur "position" will be 3.

您尝试过Sendkeys()吗?

driver.findElement(By.xpath("//div[@role='combox']")).sendKeys("text to select exp: selenium");

若上面并没有按预期工作,您可以尝试点击下拉菜单,然后点击该下拉菜单中的必需选项。

感谢

我能够通过首先单击显示所有选项的div,然后单击所需选项来解决这个问题。

感谢大家的建议。

最新更新