简体   繁体   中英

Not able to change select box value using select class in Java/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>

I am not able to change the value of the select box. By default value 1 is selected. If I manually changed it to 5 then the following html code changes the value from 1 to 5.

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

But the option tag attribute selected hasn't changed. The select tag is invisible.

If following code is used then an exception appears.

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

您是否尝试过使用SelectByValue而不是SelectByVisibleText

You mention that the select tag is invisble and that's why driver gives you the error that since it is not visible, you cannot interact with it.

Selenium used to allow interaction with hidden elements but not webdriver as it wants to more appropriately simulate user interaction.

To achieve this in webdriver, you need to make the select tag visible first by doing the operation that makes it visible on the page and then use selectbylabel. Also your xpath seems to be considering the span id whereas select tag itself has an id to identify it. I would suggest using select's id directly instead of going the relative way.

Use This :

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

If then too you get visibility exception then you would have to go with JavaScript Executor .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM