如果我想选择下拉框的选项,有几种方法可以做到这一点.我一直用:
driver.findElement(By.id("selection")).sendKeys("Germany");
Run Code Online (Sandbox Code Playgroud)
但这并不是每次都有效.有时选择另一个选项.所以我google了一下,发现这段代码每次都有效:
WebElement select = driver.findElement(By.id("selection"));
List<WebElement> options = select.findElements(By.tagName("option"));
for (WebElement option : options) {
if("Germany".equals(option.getText()))
option.click();
}
Run Code Online (Sandbox Code Playgroud)
但这确实很慢.如果我有一个包含很多项目的长列表,那真的需要花费太多时间.所以我的问题是,是否有一个解决方案,每次都有效并且速度快?
我试图熟悉新的ruby selenium-webdriver,因为它看起来比以前版本的selenium和随之而来的ruby驱动程序更直观.另外,我无法让旧的selenium在windows中使用ruby 1.9.1,所以我想我会寻找替代方案.到目前为止,我已经用我的脚本完成了这个:
require "selenium-webdriver"
driver = Selenium::WebDriver.for :firefox
driver.get "https://example.com"
element = driver.find_element(:name, 'username')
element.send_keys "mwolfe"
element = driver.find_element(:name, 'password')
element.send_keys "mypass"
driver.find_element(:id, "sign-in-button").click
driver.find_element(:id,"menu-link-my_profile_professional_info").click
driver.find_element(:id,"add_education_btn").click
country_select = driver.find_element(:name, "address_country")
Run Code Online (Sandbox Code Playgroud)
所以基本上我正在登录我的网站,并尝试在我的用户配置文件中添加一个教育条目.我有一个带选项的选择框的引用(在country_select变量中),现在我想选择一个给定值的选项..我没有看到如何在新客户端中执行此操作.我唯一能想到的是循环遍历所有选项,直到找到我想要的那个,然后调用execute_script: http:// selenium. googlecode.com/svn/trunk/docs/api/rb/Selenium/WebDriver/Driver.html#execute_script-class_method 方法设置selectedIndex.
有没有其他方法可以做到这一点?在这里的java api for selenium 2.0/webdriver:http://seleniumhq.org/docs/09_webdriver.html 有一个这样做的例子
Select select = new Select(driver.findElement(By.xpath("//select")));
select.deselectAll();
select.selectByVisibleText("Edam");
Run Code Online (Sandbox Code Playgroud)
除非我遗漏了某些东西,否则ruby版本似乎没有这个功能.任何帮助,将不胜感激.