Select Operation in Selenium for Html Select Lists

By | 10/07/2015

If you have any Select/Option list in your web page, you can do selection by Select operation in Selenium. No need to to go to each option element by any identifier. At below, there are code both for Pyhton and Java. Be Careful to import Select package in your code.

Python:

# -*- coding: UTF-8 -*-
from selenium import webdriver
from selenium.webdriver.support.ui import Select

driver = webdriver.Firefox()
driver.implicitly_wait(30)
driver.set_page_load_timeout(30)
driver.maximize_window()

driver.get("http://mahsumakbas.net/selenium/index.html")

Select(driver.find_element_by_id("selectByIndex")).select_by_index(1)

Select(driver.find_element_by_id("selectByValue")).select_by_value("value3")

Select(driver.find_element_by_id("selectByText")).select_by_visible_text("text4")

driver.quit()

Java:

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;

public class SelectOperations {
    static WebDriver driver = new FirefoxDriver();

    public static void main(String[] args) throws InterruptedException {

        driver.get("http://mahsumakbas.net/selenium/index.html");

        Select selIndex = new Select(driver.findElement(By.id("selectByIndex")));
        selIndex.selectByIndex(1); // it iwll select 2nd option in Select list
        // Remember that index start from 0

        Select selValue = new Select(driver.findElement(By.id("selectByValue")));
        selValue.selectByValue("value3");

        Select selText = new Select(driver.findElement(By.id("selectByText")));
        selText.selectByVisibleText("text4");

        driver.quit();
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *

*