由于“未解决的类型”错误,无法使用Webdriver运行Javascript

时间:2013-12-18 11:07:33

标签: java javascript selenium-webdriver selenium-firefoxdriver

您好我无法使用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)

4 个答案:

答案 0 :(得分:0)

看起来您正在尝试实例化一个不存在的类,即:

  WebDriver driver2 = new AnyDriverYouWant();

删除此行(它看起来不像它所需的),它应该可以工作。

答案 1 :(得分:0)

我需要强制页面等待并无条件地实例化变量,这是修改后的代码:

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();
    }

}

答案 2 :(得分:0)

我从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();

答案 3 :(得分:0)

我今天遇到了这个问题。它是通过为javascriptExecutor类显式编写import语句来解决的。