【问题标题】:How to select an item from a CSS custom dropdown list using Selenium WebDriver with java?如何使用 Selenium WebDriver 和 java 从 CSS 自定义下拉列表中选择一个项目?
【发布时间】:2017-09-14 16:23:53
【问题描述】:

我想在 CSS 下拉列表中选择一个项目,但似乎没有办法,我们可以以谷歌酒店评论页面 here 为例,我如何通过 selenium 以编程方式选择最近的评论?

基本上,我希望查看按最新而不是最有用排序的所有酒店评论,但由于默认情况下按最有用排序,我需要以编程方式切换下拉列表。

我试过这种方式:

        Select select = new Select(driver.findElement(By.xpath("//*[@id=\"gsr\"]/g-lightbox/div[2]/div[3]/div/div/div/div[1]/div[3]/div[2]/g-dropdown-menu/g-popup/div[2]/g-menu")));
        select.deselectByIndex(1);

但我得到一个例外(org.openqa.selenium.support.ui.UnexpectedTagNameException)说:

Element should have been "select" but was "g-dropdown-menu"

有没有办法用 Selenium 网络驱动程序模拟这样的 CSS 下拉元素的点击?

【问题讨论】:

  • 我不确定我是否正确理解了您的问题。我能够追踪到xpath 直到//g-dropdown-menu/g-popup,但仅此而已。你能更新我们的手动步骤吗?
  • 基本上我想查看按最新而不是最有用排序的酒店的所有评论,但由于默认情况下按最有用排序,我需要以编程方式切换下拉列表。我需要做的是在最近使用 selenium 的下拉列表中选择。有什么想法吗?

标签: java css selenium xpath web-scraping


【解决方案1】:

分析:

Selenium Java API:Select.class 仅适用于使用 HTML 选择标签的下拉菜单。对于其他方式的下拉实现,如JQuery下拉插件,不支持选择类,对于此类下拉,您需要单击下拉使选项显示出来,然后选择您想要的选项。

解决方案:

public void selectSortby(String sortBy) {
  // click on dropdown to expand options
  driver.findElement(By.xpath("//div[span[text()='Sort by:']]//g-dropdown-button").click();
  // choose option
  driver.findElement(By.xpath("//g-menu-item/div[text()='"+sortBy+"']")).click();
}

【讨论】:

    猜你喜欢
    • 2012-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多