0

I am trying to locate an element within a dropdown list with Selenium. How can I do this? Attached are images which describe the situation. I want to do this using the IWebElement function.

I've tried using the following:

IWebElement Depart = driver.FindElement(By.XPath("///input[@name='fromPort' and @value='Sydney']"));

but it does not work!! How can I select Sydney from the drop-down list?

enter image description here

2

2 Answers 2

2

If the dropdown is defined with select and option tag, then you can use the SelectElement class to select the value from the dropdown.

You can use any one of the method to select the value from the dropdown Refer the Documentation

SelectByIndex - Select an option by the index

SelectByText - Select an option by the text displayed.

SelectByValue - Select an option by the value.

You need to pass the dropdown element to the SelectElement class and can use any one of the above method

Code:

IWebElement Depart = driver.FindElement(By.Name("fromPort"));
SelectElement select=new SelectElement(Depart);

Option 1:

 select.SelectByText("Sydney");

Option 2:

 select.SelectByValue("Sydney");

Option 3:

 select.SelectByIndex(8);//Sydney value index is 8
Sign up to request clarification or add additional context in comments.

1 Comment

@Novice_29: Please accept the answer by clicking on the tick button
1

Use the following code for that:

using OpenQA.Selenium.Support.UI;


var selectElement = new SelectElement(driver.FindElement(By.Name("fromPort")));
selectElement.SelectByText("London");

Hope it helps you!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.