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?
-
2Possible duplicate of How to select an option from drop down using Selenium WebDriver C#?Guy– Guy2018年07月29日 08:33:33 +00:00Commented Jul 29, 2018 at 8:33
-
Was my answer helpful?Ratmir Asanov– Ratmir Asanov2018年07月29日 13:16:36 +00:00Commented Jul 29, 2018 at 13:16
2 Answers 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
1 Comment
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!