我正在为我的网络测试选择一个选项。可以在这里找到一个示例:http://www.tizag.com/phpT/examples/formex.php
除了选择选项部分之外,所有的工作都很好。如何按值或按标签选择选项?
我的代码:
using OpenQA.Selenium.Firefox;
using OpenQA.Selenium;
using System.Collections.ObjectModel;
using System.Text.RegularExpressions;
using System.Threading;
using System.Diagnostics;
using System.Runtime.InteropServices;
class GoogleSuggest
{
static void Main()
{
IWebDriver driver = new FirefoxDriver();
//Notice navigation is slightly different than the Java version
//This is because 'get' is a keyword in C#
driver.Navigate().GoToUrl("http://www.tizag.com/phpT/examples/formex.php");
IWebElement query = driver.FindElement(By.Name("Fname"));
query.SendKeys("John");
driver.FindElement(By.Name("Lname")).SendKeys("Doe");
driver.FindElement(By.XPath("//input[@name='gender' and @value='Male']")).Click();
driver.FindElement(By.XPath("//input[@name='food[]' and @value='Chicken']")).Click();
driver.FindElement(By.Name("quote")).Clear();
driver.FindElement(By.Name("quote")).SendKeys("Be Present!");
driver.FindElement(By.Name("education")).SendKeys(Keys.Down + Keys.Enter); // working but that's not what i was looking for
// driver.FindElement(By.XPath("//option[@value='HighSchool']")).Click(); not working
// driver.FindElement(By.XPath("/html/body/table[2]/tbody/tr/td[2]/table/tbody/tr/td/div[5]/form/select/option[2]")).Click(); not working
// driver.FindElement(By.XPath("id('examp')/x:form/x:select[1]/x:option[2]")).Click(); not working
}
}
发布于 2011-03-14 16:37:28
您必须从下拉列表中创建一个选择元素对象。
using OpenQA.Selenium.Support.UI;
// select the drop down list
var education = driver.FindElement(By.Name("education"));
//create select element object
var selectElement = new SelectElement(education);
//select by value
selectElement.SelectByValue("Jr.High");
// select by text
selectElement.SelectByText("HighSchool");
更多信息here
发布于 2015-02-21 12:50:47
补充一点-我遇到了一个问题,在将OpenQA.Selenium.Support.UI绑定安装到C#项目中后,Selenium.NET名称空间不可用。后来发现,我们可以通过运行以下命令轻松安装最新版本的Selenium WebDriver支持类:
Install-Package Selenium.Support
在NuGet包管理器控制台中,或从NuGet管理器安装Selenium.Support。
发布于 2012-05-26 07:13:47
另一种方式可以是这种方式:
driver.FindElement(By.XPath(".//*[@id='examp']/form/select[1]/option[3]")).Click();
您可以更改optionx中的索引,根据要选择的元素的数量更改x。
我不知道这是不是最好的方法,但我希望这对你有帮助。
https://stackoverflow.com/questions/5278281
复制相似问题