Selenium - PhantomJS:NoSuchElementException

时间:2018-01-06 12:11:44

标签: java selenium phantomjs

我尝试使用Selenium登录facebook。当我使用ChromeDriver作为WebDriver时,下面的代码完全正常。但是,我想在没有弹出浏览器窗口的情况下运行它,所以我想使用PhantomJS。 PhantomJS找不到表单元素,并抛出NoSuchElement异常。

代码:

public class TestPhantomjsDriver {

public static void main(String[] args) {

    TestPhantomjsDriver example = new TestPhantomjsDriver();

    example.runPhantomjsWebDriver();

}

public void runPhantomjsWebDriver() {
    try {           
        DesiredCapabilities caps = new DesiredCapabilities();
        ((DesiredCapabilities) caps).setJavascriptEnabled(true);                
        ((DesiredCapabilities) caps).setCapability(
                PhantomJSDriverService.PHANTOMJS_EXECUTABLE_PATH_PROPERTY,
                "C:/Users/user1/Downloads/phantomjs-2.1.1-windows/phantomjs-2.1.1-windows/bin/phantomjs.exe"
            );                      

        // Initiate PhantomJSDriver.
        WebDriver driver = new PhantomJSDriver(caps);
        // Initiate ChromeDriver
         //String chromeDriverPath = "C:\\Users\\user1\\Downloads\\chromedriver_win32\\chromedriver.exe";
         //System.setProperty("webdriver.chrome.driver", chromeDriverPath);
         //WebDriver driver = new ChromeDriver();           

        driver.manage().window().maximize();

        driver.get("https://www.facebook.com");

        Thread.sleep(3000);

        driver.manage().window().maximize();
        WebElement emailElement = driver.findElement(By.id("email"));
        WebElement passwordElement = driver.findElement(By.id("pass"));
        emailElement.sendKeys("xxxx@gmail.com");
        passwordElement.sendKeys("xxxx");

        driver.findElement(By.id("loginbutton")).click();


}

}

例外:

org.openqa.selenium.NoSuchElementException: {"errorMessage":"Unable to find element with id 'email'","request":{"headers":{"Accept-Encoding":"gzip,deflate","Connection":"Keep-Alive","Content-Length":"30","Content-Type":"application/json; charset=utf-8","Host":"localhost:34242","User-Agent":"Apache-HttpClient/4.5.3 (Java/1.8.0_101)"},"httpVersion":"1.1","method":"POST","post":"{\"using\":\"id\",\"value\":\"email\"}","url":"/element","urlParsed":{"anchor":"","query":"","file":"element","directory":"/","path":"/element","relative":"/element","port":"","host":"","password":"","user":"","userInfo":"","authority":"","protocol":"","source":"/element","queryKey":{},"chunks":["element"]},"urlOriginal":"/session/b38f4c20-f2d8-11e7-9f9c-5d9ac6119c58/element"}}

1 个答案:

答案 0 :(得分:0)

我和PhantomJS有同样的问题。尝试打印HTML页面源:

driver.getPageSource()

可能是PhantomJS没有像Chrome那样获得相同的页面源,在这种情况下,有些元素缺失。

这是我原来的问题,我遇到了同样的问题:Selenium + PhantomJS - missing elements in Page Source