【问题标题】:How to use selenium webdriver to select an option of Bootstrap select dropdown menu?如何使用 selenium webdriver 选择 Bootstrap 选择下拉菜单的选项?
【发布时间】:2017-10-29 11:37:15
【问题描述】:

我必须从https://www.parcelhero.com 的下拉列表中选择一个国家,但是当我使用下面的代码时,有时它有时不起作用,给出 Element not found(xpath("//*[@id=' dvQuoteFrom']/div/button"))

driver.findElement(By.xpath("//*[@id='dvQuoteFrom']/div/button")).click();

        Thread.sleep(4000);

       WebElement txt = driver.findElement(By.xpath("html/body/div[14]/div/div/input"));
txt.sendKeys("Great Britain");
List <WebElement> InnerDropdown1 =driver.findElements(By.xpath("//*[@class='active']"));
       for(WebElement option1 :  InnerDropdown1)
        {   System.out.println(option1.getText());

        if(option1.getText().contains("Great Britain")) {
          option1.click();
           break; 
       }
        }

当我使用 WebElement txt = driver.findElement(By.className("bs-searchbox"));然后我也可以找到元素错误。

请帮我从国家/地区下拉列表中选择我喜欢的国家/地区?

【问题讨论】:

    标签: select selenium-webdriver drop-down-menu bootstrapping


    【解决方案1】:

    尝试这样做。我已经更改了您的一些定位器,并在您提到的页面上进行了测试。

    public void foo() {
        driver.get("https://www.parcelhero.com/");
    
        //This will be your dropdown button. This needs to be clicked first.
        driver.findElement(By.xpath("//button[contains(@data-id,'ConsignorAddressCountryId')]")).click();
    
        //These are your input boxes. I found 3 input boxes on the same page having the same identifiers. We dont want to rely on using index based xpath so here we'll get all instances of input boxes.
        List<WebElement> elems = driver.findElements(By.xpath("//*[contains(@class,'bs-searchbox')]//input"));
        for (WebElement elem : elems) {
    
            //Here we check if the input box is visible. If I'm not mistaken, there will only be 1 visible input box at a time because you have to click on the dropdown button first.
            if (elem.isDisplayed()) {
                //If visible, just enter your country of choice
                elem.sendKeys("American Samoa");
                //Assuming you always enter exact match string for your test, you can use the org.openqa.selenium.Keys for sendKeys()
                elem.sendKeys(Keys.ENTER);
                break;
            }
        }
    }
    

    【讨论】:

    • 谢谢,我去看看
    猜你喜欢
    • 1970-01-01
    • 2014-02-26
    • 2018-02-04
    • 1970-01-01
    • 1970-01-01
    • 2018-02-17
    • 2015-06-16
    • 2016-07-28
    相关资源
    最近更新 更多