我已经通过对stackoverflow上类似问题的答案,但没有答案为我工作。与大多数答案的具体区别在于select元素中的javascript回调。我曾尝试选择对象,使用索引值和文本定位器,没有人会选择正确的选项,所有由于JavaScript回调相信Selenium没有选择由于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定位器。
在这两个情况下,选择控制作品的选择,选项的选择似乎工作,但要选择的点击并不会引起。
我想下面的选项为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'类?如果试过可以分享它? –
你能否在公共网址上复制这个问题? –