无法在Javascript功能启用按钮上执行Selenium WebDriver命令

Unable to execute Selenium WebDriver command on Javascript function enabled button

本文关键字:执行 Selenium WebDriver 命令 按钮 启用 Javascript 功能      更新时间:2023-09-26

我指的是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

按钮位于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();