操作页面元素WebElement—Selenium自动化测试指南(4)

发表于:2013-8-29 11:19

字体: | 上一篇 | 下一篇 | 我要投稿

 作者:赵卓    来源:51Testing软件测试网

  程序清单5-33  C#代码

IWebDriver driver = new FirefoxDriver();
INavigation navigation = driver.Navigate();
navigation.GoToUrl(http://www.baidu.com);
navigation.GoToUrl("http://tieba.baidu.com/f/search/adv");
IWebElement select = driver.FindElement(By.Name("sm"));
string targetText = "按相关性排序";
System.Collections.Generic.IList<IWebElement> options = select.FindElements(By.TagName("option"));
for (int i = 0; i < options.Count; i++)
{
if (options[i].Text == targetText)
{
options[i].Click();
}
}

  程序清单5-34  Java代码

WebDriver driver = new FirefoxDriver();
Navigation navigation = driver.navigate();
navigation.to(http://www.baidu.com);
navigation.to("http://tieba.baidu.com/f/search/adv");
WebElement select = driver.findElement(By.name("sm"));
String targetText = "按相关性排序";
java.util.List<WebElement> options = select.findElements(By.tagName("option"));
for (int i = 0; i < options.size(); i++)
{
if (options.get(i).getText().equals(targetText))
{
options.get(i).click();
}
}

  实现的原理就是先找到Select元素,然后获取它的所有选项,接着遍历这些选项并找出和要选择的文本相同的选项,最后单击它。

  5.6.2  SendKeys(text)

  SendKeys()方法用于给input元素输入文本。例如,百度首页有搜索文本框,如图5-40所法。

  图5-40  百度首页搜索文本框

  要操作该文本框,需先定位该页面元素,然后使用SendKeys()方法输入指定内容,代码如程序清单5-35或程序清单5-36所示。

  程序清单5-35  C#代码

IWebDriver driver = new FirefoxDriver();
INavigation navigation = driver.Navigate();
navigation.GoToUrl(http://www.baidu.com);
IWebElement baiduTextBox = driver.FindElement(By.Id("kw"));
baiduTextBox.SendKeys("找到文本框");

  程序清单5-36  Java代码

WebDriver driver = new FirefoxDriver();
Navigation navigation = driver.navigate();
navigation.to(http://www.baidu.com);
WebElement baiduTextBox = driver.findElement(By.id("kw"));
baiduTextBox.sendKeys("找到文本框");

  找到文本框之后,执行“baiduTextBox.SendKeys("找到文本框");”,在搜索文本框中输入“找到文本框”。

  执行结果如图5-41所示。

  图5-41  执行结果

54/5<12345>
《2023软件测试行业现状调查报告》独家发布~

关注51Testing

联系我们

快捷面板 站点地图 联系我们 广告服务 关于我们 站长统计 发展历程

法律顾问:上海兰迪律师事务所 项棋律师
版权所有 上海博为峰软件技术股份有限公司 Copyright©51testing.com 2003-2024
投诉及意见反馈:webmaster@51testing.com; 业务联系:service@51testing.com 021-64471599-8017

沪ICP备05003035号

沪公网安备 31010102002173号