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

Ratmir Asanov
6,4795 gold badges29 silver badges44 bronze badges
asked Jul 29, 2018 at 8:25
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
answered Jul 29, 2018 at 9:49

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!

answered Jul 29, 2018 at 8:35

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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