【发布时间】:2016-08-15 15:04:47
【问题描述】:
我已通读 stackoverflow 上类似问题的答案,但没有一个答案对我有用。大多数答案的具体区别在于 select 元素中的 javascript 回调。我试过选择对象,使用索引、值和文本的定位器,没有一个会选择正确的选项,这都是由于我相信的 javascript 回调
这是我要从中选择的元素:
<select name="ctl0" onchange="javascript:setTimeout('__doPostBack(\'ctl0\',\'\')', 0)" id="ctl0" style="width:205px;margin-left:30px;">
<option value="0">Option 0</option>
<option selected="selected" value="1">Option 1</option>
<option value="2">Option 2</option>
</select>
这是我的代码:
driver.findElement(By.id("ctl0")).click();
driver.findElement(By.xpath("//select[@id=\"ctl0\"]/option[@value=\"1\"]")).click();
结果没有差异的替代方法:
driver.findElement(By.id("ctl0")).click();
Select select = new Select(driver.findElement(By.id("ctl0")));
WebElement elem = select.getOptions().get(1);
System.out.println(elem.getText());
elem.click();
在你回答之前,我必须根据其他人点击这两个,因为回调似乎欺骗了 Select 对象,因此显式点击和 XPath 定位器。
select 控件的选择在这两种情况下都有效,option 的选择似乎有效,但单击不会导致它被选中。
我尝试了下面的 javascript 选项,同样的问题
WebElement el = driver.findElement(By.id("ctl0"));
String jsScript = "showDropdown = function (element) "
+ "{"
+ " var event; "
+ " event = document.createEvent('MouseEvents'); "
+ " event.initMouseEvent('mousedown', true, true, window, 1, 0,0,0,0,false,false,false,false,0,null); "
+ " element.dispatchEvent(event); "
+ "}; "
+ "showDropdown(arguments[0]);";
((JavascriptExecutor)driver).executeScript(jsScript,el);
WebElement elem = el.findElement(By.xpath(".//option[@value = '1']"));
System.out.println("Option visible text is " + elem.getText());
elem.click();
该网站不公开,我无法控制它。请注意,以下解决方案中指定的 initMouseEvent 并不具有所有必需的参数。我想我说得对。 initMouseEvent 现在也被弃用了。
我最初使用 Selenium IDE 来记录操作。这就是它为 Java 导出它的方式:
new Select(driver.findElement(By.id("ctl0"))).selectByVisibleText("Option 1");
driver.findElement(By.cssSelector("option[value=\"1\"]")).click();
读完后-Preserve onchange for a dropdown list when setting the value with Javascript
我试过这个(也有未装饰窗口前缀的功能):
new Select(driver.findElement(By.id("ctl0"))).selectByValue("1");
String jsScript = "window.__doPostBack(arguments[0],'');";
((JavascriptExecutor)driver).executeScript(jsScript,"ctl0");
但是得到这个:
org.openqa.selenium.WebDriverException: TypeError: window.__doPostBack is not a function (WARNING: The server did not provide any stacktrace information)
想法?
【问题讨论】:
-
您是否尝试过使用
Select类??如果试过了,你能分享一下吗?? -
你能在公共 URL 上复制这个问题吗?
标签: java selenium xpath selenium-webdriver