0
votes

I'm writing a Selenium script that containing a drop down list.

<select id="seats" class="form-control" name="seats">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="3">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>
<option value="10">10</option>
<option value="11">11</option>
<option value="12">12</option>
<option value="13">13</option>
<option value="14">14</option>
<option value="15">15</option>
<option value="16">16</option>
<option value="17">17</option>
<option value="18">18</option>
<option value="19">19</option>
<option value="20">20</option>
<option value="21">22</option>
<option value="23">24</option>
<option value="25">25</option>
<option value="26">26</option>
<option value="27">27</option>
<option value="28">28</option>
<option value="29">29</option>
<option value="30">30</option>
</select>

I've looked several answers in stack overflow to select a value form dropdown box and every time I failed. Even tried to get xpath from Selenium IDE. in that case I got same Relative XPath to both dropdown and the value.

Here is the code I'm currently using.

driver.findElement(By.id("seats")).click();
driver.findElement(By.xpath("//form[@id='side-form']/div/div/div/div/div[3]/div/select")).click();

Here what i need to select is 4. but, it selecting 1.

Can someone tell me how to select 4 from my dropdown. Any help would be appreciated.

Thanks in advance. :)

2

2 Answers

1
votes

It is a bit awkward that your dropdown has 2 options with the same value. Anyway, here is one possible XPath which will return the last option of certain value, from dropdown with id equals 'seats' :

driver.findElement(By.xpath("//select[@id='seats']/option[@value='3'][last()]")).click();
1
votes

Please try below sample

new Select(driver.findElement(By.id("seats"))).selectByValue("4");

Edit

WebElement select = driver.findElement(By.id("seats"));
 List<WebElement> allOptions = select.findElements(By.tagName("option"));
 for (WebElement option : allOptions) {
        if(option.getText().equals("4")){
           option.click();
        }
 }