嗨,我无法使用Web驱动程序运行JavaScript,因为Unresolved compilation problem
,有人能指出我出错的地方所以我可以在运行selenium web驱动程序脚本时运行一个真正简单的JavaScript行吗?
package Check;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class java {
public static void main(String[] args) {
// TODO Auto-generated method stub
FirefoxDriver driver = new FirefoxDriver();
driver.get("https://www.google.co.uk/search?q=dreams");
WebDriver driver2 = new AnyDriverYouWant();
JavascriptExecutor js;
if (driver instanceof JavascriptExecutor) {
js = (JavascriptExecutor)driver;
}
js.executeScript("function showAlert() { alert('success'); }; showAlert()");
driver.quit();
}
}
错误详情:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
AnyDriverYouWant cannot be resolved to a type
at Check.java.main(java.java:13)
看起来您正在尝试实例化一个不存在的类,即:
WebDriver driver2 = new AnyDriverYouWant();
删除这一行(它看起来不像它需要),它应该工作。
我需要强制页面等待并无条件地实例化变量,这是修改后的代码:
package Check;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.firefox.FirefoxDriver;
public class jave {
public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
FirefoxDriver driver = new FirefoxDriver();
driver.get("https://www.google.co.uk/search?q=dreams");
//WebDriver driver2 = new AnyDriverYouWant();
JavascriptExecutor js = (JavascriptExecutor)driver;
js.executeScript("function showAlert() { alert('success'); }; showAlert()");
Thread.sleep(5000);
driver.quit();
}
}
我从here和最新的selenium jar文件(2.44)下载了最新的chrome驱动程序,并使用此代码,我可以使元素可点击:
// Find an element and define it
WebElement elementToClick = D9.findElement(By.xpath("xpathcode"));
// Scroll the browser to the element's Y position
((JavascriptExecutor) D9).executeScript("window.scrollTo(0,"+elementToClick.getLocation().y+")");
// Click the element
elementToClick.click();
我今天遇到了这个问题。它是通过为javascriptExecutor类显式编写import语句来解决的