使用selenium webdriver从下拉列表中选择值

时间:2017-10-05 14:22:01

标签: selenium selenium-webdriver

我正在尝试使用selenium webdriver从下拉列表中选择一个值,但它只是打开下拉列表并立即将其关闭。

以下是webdriver的代码:

driver.findElement(By.cssSelector("span.k-select  ")).click();
        Thread.sleep(3000);
        driver.findElement(By.xpath("//li[@class='k-item'][.='Revenue per click']")).click();

这是来自浏览器的下拉列表的HTML代码:

<div class="controls">  
    <span class="k-widget k-dropdown k-header kendo-input span8 ddFix" unselectable="on">
      <span unselectable="on" class="k-dropdown-wrap k-state-default">
         <span unselectable="on" class="k-input">Select revenue type...
         </span>
         <span unselectable="on" class="k-select">
            <span unselectable="on" class="k-icon k-i-arrow-s">select</span>
         </span>
       </span>
      <input name="revenueType" id="revenueType" class="kendo-input span8 ddFix" data-role="dropdownlist" style="display: none;">
  </span>
</div>

 <div class="k-animation-container km-popup">
      <div class="k-list-container k-popup k-group k-reset" id="revenueType-list" data-role="popup">
          <ul unselectable="on" class="k-list k-reset" tabindex="-1" role="listbox" aria-hidden="true" id="revenueType_listbox" aria-live="off" style="overflow: auto;">
              <li tabindex="-1" role="option" unselectable="on" class="k-item">Select revenue type...</li>
              <li tabindex="-1" role="option" unselectable="on" class="k-item">Revenue per action</li>
              <li tabindex="-1" role="option" unselectable="on" class="k-item">Revenue per click</li>
              <li tabindex="-1" role="option" unselectable="on" class="k-item">Revenue per sale</li>
              <li tabindex="-1" role="option" unselectable="on" class="k-item">Revenue per action + Revenue per sale</li>
              <li tabindex="-1" role="option" unselectable="on" class="k-item">Revenue per mile</li>
          </ul>
      </div>
    </div>

2 个答案:

答案 0 :(得分:0)

没有上下文就很难调试,但是:

  1. 您的定位器无效,请尝试使用:

    By.xpath("//li[text()='Revenue per click']")
    

    由于只有一个项目具有该文本,因此应该足够了。如果您仍想在选择器中加入@class,请使用

    By.xpath("//li[@class='k-item' and text()='Revenue per click']")
    
  2. 尝试使用javascript将不可选择的内容更改为使用javascript执行程序关闭。

答案 1 :(得分:0)

执行点击操作后获取下拉文本值

subdropdown_child = navigationDriver.findElements(By.cssSelector("select#ctl00_SPWebPartManager1_g_c873566a_540c_4681 option");                                 
for (Element subchild : subdropdown_child) 
  {    
     dropdown_value = subchild.text();
     new Select(navigationDriver.findElementByCssSelector("select#ctl00_SPWebPartManager1_g_c873566a_540c_4681_")).selectByVisibleText(dropdown_value);
  }