程序清单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 执行结果