【问题标题】:How to select a combobox value with Selenium WebDriver where it's a div with role of combobox如何使用 Selenium WebDriver 选择一个组合框值,其中它是一个具有组合框角色的 div
【发布时间】:2016-04-02 02:45:47
【问题描述】:

我的 HTML 代码有一个 div 标签,其角色为组合框,即

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

我正在尝试使用 java 通过 selenium 驱动程序从组合框中选择一个项目。

我尝试使用此处推荐的“选择”类: How to select a dropdown value in Selenium WebDriver using Java

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

"UnexpectedTagNameException: 元素本应被选中,但却是 div"

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

有没有办法解决这个问题?

【问题讨论】:

  • 如果下拉列表是使用select html tag 构建的,您只能使用Select 类,否则您需要使用其他方法来处理下拉列表。我可以要你的 HTML 片段和你尝试过的代码吗?
  • html 是:
    我试过的代码是:Select dropdown = new Select(driver.findElement(By. id("search_key.combobox")));
  • 请为组合框发布 html

标签: java html selenium selenium-webdriver


【解决方案1】:

因为没有

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.

【讨论】:

    【解决方案2】:

    您是否尝试过使用 Sendkeys()?

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

    如果上面没有按预期工作,您可以尝试单击下拉菜单并单击该下拉菜单中的所需选项。

    谢谢

    【讨论】:

    • html 是:
      我试过的代码是:Select dropdown = new Select(driver.findElement(By. id("search_key.combobox")));我也尝试过使用 SendKeys,但它不起作用。
    • @ParagMahajan,它看起来像普通的 div,因为在提供的 html 中没有选项。所以请尝试点击该div,然后选项将显示在下拉列表中,然后再次点击所需选项。
    【解决方案3】:

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

    感谢大家的建议。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-01-22
      • 2017-04-19
      • 1970-01-01
      • 2013-05-22
      • 1970-01-01
      • 1970-01-01
      • 2019-10-20
      • 1970-01-01
      相关资源
      最近更新 更多