无法使用Java / webDriver中的select类更改选择框值

时间:2012-11-26 10:54:29

标签: java javascript xpath selenium webdriver

<span id="outDuration" class="check_duration last flL" onclick="hideCalendar('#pickUpDate');">
      <label style="width:95px">
      <span class="Class-Outmatch">
             <select id="duration" class="selectBox"  tabindex="7" name="duration">
                         <option selected="selected" value="1">1</option>
                         <option value="2">2</option>
                         <option value="3">3</option>
                         <option value="4">4</option>
                         <option value="5">5</option>
                         <option value="6">6</option>
                         <option value="7">7</option>
                         <option value="8">8</option>
                         <option value="9">9</option>
            </select>
            <span class="left_part flL firefinder-match"></span>
            <span class="selectBox center_part flL selectBox-dropdown" tabindex="7">
                         <span class="selectBox-label">5</span>

我无法更改选择框的值。 默认情况下,选择值1。 如果我手动将其更改为5,则以下html代码会将值从1更改为5.

<span class="selectBox-label">5</span> 

但是选项标记属性selected没有改变。 select标签是不可见的。

如果使用以下代码,则会出现异常。

Select select = driver.findElement(By.xpath("//span[@id='outDuration']/span/select")).SelectByVisibleText("5");

Exception: Element is not currently visible and so may not be interacted with

3 个答案:

答案 0 :(得分:1)

您是否尝试过使用SelectByValue代替SelectByVisibleText

答案 1 :(得分:0)

你提到select标签是不可见的,这就是驱动程序为你提供错误的原因,因为它不可见,你无法与之交互。

Selenium曾经允许与隐藏元素交互但不能与webdriver交互,因为它希望更适当地模拟用户交互。

要在webdriver中实现此目的,您需要首先通过执行使其在页面上可见的操作然后使用selectbylabel来使select标签可见。你的xpath似乎也在考虑span id,而select tag本身有一个id来识别它。我建议直接使用select的id而不是相对的方式。

答案 2 :(得分:0)

使用此:

Select select=new Select(Utils.driver.findElement(By.xpath("//span[@id='outDuration']//select[@id='duration']")));
select.deselectAll();
select.selectByVisibleText("5");

如果那时你也会获得可见性异常,那么你必须使用JavaScript Executor