[英]How do I find and select a dropdown value with Selenium using C# in Visual Studio 2017
I am trying to locate an element within a dropdown list with Selenium.我正在尝试使用 Selenium 在下拉列表中定位一个元素。 How can I do this?
我怎样才能做到这一点? Attached are images which describe the situation.
附上描述情况的图片。 I want to do this using the IWebElement function.
我想使用 IWebElement 函数来做到这一点。
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?
如何从下拉列表中选择悉尼?
If the dropdown is defined with select and option tag, then you can use the SelectElement
class to select the value from the dropdown.如果下拉列表是用 select 和 option 标签定义的,那么您可以使用
SelectElement
类从下拉列表中选择值。
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 SelectByIndex - 按索引选择一个选项
SelectByText - Select an option by the text displayed. SelectByText - 通过显示的文本选择一个选项。
SelectByValue - Select an option by the value. SelectByValue - 按值选择一个选项。
You need to pass the dropdown element to the SelectElement
class and can use any one of the above method您需要将下拉元素传递给
SelectElement
类,并且可以使用上述任何一种方法
Code:代码:
IWebElement Depart = driver.FindElement(By.Name("fromPort"));
SelectElement select=new SelectElement(Depart);
Option 1:选项1:
select.SelectByText("Sydney");
Option 2:选项 2:
select.SelectByValue("Sydney");
Option 3:选项 3:
select.SelectByIndex(8);//Sydney value index is 8
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!希望对你有帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.