【问题标题】:select a value from drop down in selenium java webdriver using使用 selenium java webdriver 从下拉列表中选择一个值
【发布时间】:2013-07-29 11:04:13
【问题描述】:

如何使用 selenium java webdriver 使用 xpath 从下拉列表中选择一个值? 根据下拉列表中选择的选项,会出现字段。因此我不需要在其中输入值。我的问题是在下拉列表中选择选项后我没有得到字段。经过很长一段时间后,它出现,意味着同时出现错误

【问题讨论】:

  • 你有代码吗?
  • 需要使用等待元素策略,直到字段出现

标签: java selenium-webdriver webdriver ui-automation


【解决方案1】:

您可以单击下拉菜单并等待选项显示,然后您可以从中单击选项。

Select select = new Select(driver.findElement(By.id("drop_down_id")));

select.selectByIndex(`index_value_of_option`);

【讨论】:

    【解决方案2】:

    Jyotsna... 您的脚本需要等到该字段出现。为此,您需要使用任何等待条件。

    隐式等待

    driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
    

    或睡眠状况

    Thread.sleep(2000);
    

    或者你可以使用 Fluent wait(根据我的建议是最好的)

    public WebElement fluentWait(final By locator) {
        Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)
                .withTimeout(30, TimeUnit.SECONDS)
                .pollingEvery(5, TimeUnit.SECONDS)
                .ignoring(NoSuchElementException.class);
    
        WebElement foo = wait.until(new Function<WebDriver, WebElement>() {
            public WebElement apply(WebDriver driver) {
                return driver.findElement(locator);
            }
        });
    
        return  foo;
    };
    

    fluentWait 函数返回您找到的网页元素。来自 fluentWait 的文档:Wait 接口的一个实现,它可以动态配置其超时和轮询间隔。每个 FluentWait 实例定义等待条件的最长时间,以及检查条件的频率。此外,用户可以将等待配置为在等待时忽略特定类型的异常,例如在页面上搜索元素时的 NoSuchElementExceptions。详情可获取here

    在您的情况下使用 `fluentWait 如下:

    WebElement textbox = fluentWait(By.id("textbox"));
    

    【讨论】:

      【解决方案3】:

      打开浏览器、加载 URL 和从下拉列表中选择值的示例语句

      static WebDriver driver;
      System.setProperty("webdriver.ie.driver","C:\\(Path)\\IEDriverServer.exe");
      driver = new InternetExplorerDriver();
      driver.manage().window().maximize();
      
      driver.get("EnterURLHere");          
      driver.manage().timeouts().implicitlyWait(30,TimeUnit.SECONDS);
      
      Select value1 = new Select(driver.findElement(By.id("LocateId")));    
      value1.selectByVisibleText("ValueToBeSelected");    //Select Character from dropdown list
      

      【讨论】:

        【解决方案4】:

        您可以添加等待,以便解决延迟加载的问题。

        driver.manage().timeouts().implicitlyWait(20,TimeUnit.SECONDS);
        

        或者,

        Thread.sleep(2000);
        

        对于从下拉列表中选择,有多种方式可供选择:

        Select dropdown = new Select(driver.findElement(By.id(""))); // By id
        dropdown.selectByVisibleText(""); // By Visible text
        dropdown.selectByIndex(1); // By index 
        

        【讨论】:

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