【问题标题】:Unable to execute Selenium WebDriver command on Javascript function enabled button无法在启用 Javascript 功能的按钮上执行 Selenium WebDriver 命令
【发布时间】:2016-06-25 03:59:21
【问题描述】:

我指的是http://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_onclick_copy。单击按钮时,应该将 field1 中的值复制到 field2。我试图用 selenium webdriver 自动化它。 我正在使用WebDriver 命令作为:

driver.get("http://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_onclick_copy");
driver.findElement(By.xpath(".//button[@onclick='myFunction()']")).click();

但我得到了错误:

org.openqa.selenium.NoSuchElementException: Unable to locate element: {"method":"xpath","selector":".//button[@onclick='myFunction()']"}
Command duration or timeout: 20.11 seconds

之后我尝试了:

JavascriptExecutor jse = (JavascriptExecutor)driver;
jse.executeScript("document.getElementById(\"field2\").value = document.getElementById(\"field1\").value;");

这次我得到了错误:

org.openqa.selenium.WebDriverException: document.getElementById(...) is null

【问题讨论】:

  • 感谢 JeffC 格式化问题

标签: javascript java selenium


【解决方案1】:

您的按钮位于 iframe 内。在找到元素之前,您必须切换到框架。 见以下代码:

driver.get("http://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_onclick_copy");  
driver.switchTo().frame(driver.findElement(By.id("iframeResult"))); 
driver.findElement(By.xpath(".//button[@onclick='myFunction()']")).click();

【讨论】:

  • 现在它也适用于 JavaScript:driver.switchTo().frame(driver.findElement(By.id("iframeResult")));JavascriptExecutor jse = (JavascriptExecutor)driver;jse.executeScript( "返回 document.getElementById(\"field2\").value = document.getElementById(\"field1\").value;");
  • @MLShivaPrasad 谢谢,我已经相应地更新了答案。
猜你喜欢
  • 1970-01-01
  • 2013-10-06
  • 2013-11-02
  • 1970-01-01
  • 1970-01-01
  • 2019-04-20
  • 1970-01-01
  • 2017-08-11
  • 2013-10-17
相关资源
最近更新 更多