简体   繁体   中英

How to select an option from the dropdown as per the HTML through Selenium and Java

This is My HTML:

<tbody>
  <tr>
    <td colspan="2" style="text-align:center;font-weight:bold;padding-bottom:10px;">You     have Statewide Access<br>Please select the district in which you want to    operate</td>
  </tr> 
  <tr> 
    <td style="text-align:right;width:50%;font-weight:bold;padding-right:10px;"><label      for="districtOption">Select District</label></td>
    <td style="text-align:left;width:50%;">
      <select id=`district Option` name="district Option" size="0"                  alt="Select District" tab index="1">
        <option value="00" selected="">-- SELECT --</option>
        <option value="01"> A1 </option>
        <option value="02"> A2 </option>
      </select>
    </td>
  </tr>

My First Try:

Select select = new Select(driver.findElement(By.xpath("//select[@id='distrctOption']")));
select.selectByVisibleText("A1");

Second Try:

Select dropdown = new Select(driver.findElement(By.id("districtOption")));
dropdown.selectByIndex(01);
driver.findElement(By.xpath("//[@value='Select']")).click();

Error Message in Console for every executing one Error "Exception in thread "main"

org.openqa.selenium.NoSuchElementException Unable to locate element"

*** Element info: {Using=xpath, value=//select[@id='districtOption']}

I tried all possible ways i can ?

There are no Frames in Page, but still not able to Select it.

Use

Select select = new Select(driver.findElement(By.xpath("//select[@id='district Option']")));

You are missing the space in your xpath identification.

As per the HTML you have shared to select an option from the dropdown you have to use the <select> class and the associated methods and you can use either of the following solutions:

Select dropdown = new Select(driver.findElement(By.cssSelector("select[name='district Option'][alt='Select District']")));
//Select dropdown = new Select(driver.findElement(By.xpath("//select[@name='district Option' and @alt='Select District']")));
dropdown.selectByValue("01"); //to select the option A1
dropdown.selectByValue("02"); //to select the option A2

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