Nithya Jeyapal
Nithya Jeyapal

Reputation: 5

Selenium Object Identification Issues

I have a combo box with 2 values(say Xreg and MBA). By default only one value(either Xreg or MBA) will be displayed based on a search criteria.. The xpath for Xreg is

/html/body/div/div[4]/div[2]/form/div[1]/table[2]/tbody/tr[1]/td[2]/select/option[2] 

and for MBA

/html/body/div/div[4]/div[2]/form/div[1]/table[2]/tbody/tr[1]/td[2]/select/option[3]

How do i capture the default value on page load. It might be either of them and each time i want to capture the value that is displayed by default in the combo box

Upvotes: 0

Views: 109

Answers (1)

drkthng
drkthng

Reputation: 6929

You can use Selenium's Select class for this:

// this is only an example with the code provided, usually the select element has an id and you wouldn't necessarily need xpath
By locatorToYourSelectElement = By.xpath("/html/body/div/div[4]/div[2]/form/div[1]/table[2]/tbody/tr[1]/td[2]/select");

WebElement selectElement = driver.findElement(locatorToYourSelectElement);
Select dropdown = new Select(selectElement);

// Supposing you do not have multiple selection you will get the displayed element now very easily:
WebElement currentlySelectedOption = dropdown.getFirstSelectedOption();

Upvotes: 1

Related Questions