6

我真的很生氣。我有這樣的代碼:如何使用java實現帶Selenium WebDriver的PhantomJS

public class Creazione extends TestCase { 
    private PhantomJSDriver driver; 
    private String baseUrl; 
    private boolean acceptNextAlert = true; 
    private StringBuffer verificationErrors = new StringBuffer(); 

    @Before 
    public void setUp() throws Exception { 
     File file = new File("C:/Program Files/phantomjs-1.9.7-windows/phantomjs.exe"); 
     System.setProperty("phantomjs.binary.path", file.getAbsolutePath()); 
     driver = new PhantomJSDriver(); 
     baseUrl = "http://www.gts.fiorentina.test/"; 
     driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS); 
     driver.get(baseUrl + "/Account/Login.aspx?ReturnUrl=%2f"); 
     findDynamicElement(By.id("tbUserName_I"), 2000); 
     driver.findElement(By.id("tbUserName_I")).clear(); 
     driver.findElement(By.id("tbUserName_I")).sendKeys("rogai"); 
     driver.findElement(By.id("tbPassword_I")).clear(); 
     driver.findElement(By.id("tbPassword_I")).sendKeys("Fiorentina2014!"); 
     driver.findElement(By.id("btnLogin_CD")).click(); 
     driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS); 
    } 

    @Test 
    public void testCreazione() throws Exception { 
     driver.get(baseUrl + "/SegreteriaSportiva/Calciatori.aspx"); 
     findDynamicElement(By.cssSelector("#ASPxButton1_CD > span"), 2000); 
     driver.findElement(By.cssSelector("#ASPxButton1_CD > span")).click(); 
     findDynamicElement(By.id("FrmEdit_TS_TipoPersonaId_FK_B-1"), 2000); 
     driver.findElement(By.id("FrmEdit_TS_TipoPersonaId_FK_B-1")).click(); 
     driver.findElement(By.id("FrmEdit_TS_TipoPersonaId_FK_DDD_L_LBI2T0")).click(); 
     driver.findElement(By.id("FrmEdit_Nome_I")).clear(); 
     driver.findElement(By.id("FrmEdit_Nome_I")).sendKeys("Prova"); 
     driver.findElement(By.id("FrmEdit_Cognome_I")).clear(); 
     driver.findElement(By.id("FrmEdit_Cognome_I")).sendKeys("Calciatore"); 
     driver.findElement(By.id("FrmEdit_TS_RuoloId_FK_B-1")).click(); 
     driver.findElement(By.id("FrmEdit_TS_RuoloId_FK_DDD_L_LBI3T0")).click(); 
     driver.findElement(By.id("FrmEdit_DataNascita_I")).clear(); 
     driver.findElement(By.id("FrmEdit_DataNascita_I")).sendKeys("01/01/2014"); 
     driver.findElement(By.id("FrmEdit_Cittadinanza_I")).clear(); 
     driver.findElement(By.id("FrmEdit_Cittadinanza_I")).sendKeys("italiana"); 
     driver.findElement(By.id("FrmEdit_LuogoNascita_I")).clear(); 
     driver.findElement(By.id("FrmEdit_LuogoNascita_I")).sendKeys("roma"); 
     driver.findElement(By.cssSelector("#BTN_Edit_CD > span")).click(); 
     driver.findElement(By.id("Grid_DXFREditorcol3_I")).click(); 
     driver.findElement(By.id("Grid_DXFREditorcol3_I")).sendKeys("Prova"); 
     assertEquals("Prova",driver.findElement(By.xpath("//tr[@id='Grid_DXDataRow0']/td[3]")).getText()); 
    } 
} 

執行後,我在運行時得到這些錯誤,以下是跟蹤---

org.openqa.selenium.InvalidElementStateException: {"errorMessage":"Element is not currently interactable and may not be manipulated","request":{"headers":{"Accept-Encoding":"gzip,deflate","Connection":"Keep-Alive","Content-Length":"27","Content-Type":"application/json; charset=utf-8","Host":"localhost:20497","User-Agent":"Apache-HttpClient/4.3.2 (java 1.5)"},"httpVersion":"1.1","method":"POST","post":"{\"id\":\":wdc:1402393987914\"}","url":"/clear","urlParsed":{"anchor":"","query":"","file":"clear","directory":"/","path":"/clear","relative":"/clear","port":"","host":"","password":"","user":"","userInfo":"","authority":"","protocol":"","source":"/clear","queryKey":{},"chunks":["clear"]},"urlOriginal":"/session/e4b71580-f084-11e3-959e-273aa801dd81/element/%3Awdc%3A1402393987914/clear"}} 
Command duration or timeout: 215 milliseconds 
Build info: version: '2.42.1', revision: '68b415a', time: '2014-05-29 16:17:18' 
System info: host: 'Silvio-Acer', ip: '10.10.1.122', os.name: 'Windows 7', os.arch: 'x86', os.version: '6.1', java.version: '1.7.0_55' 
Session ID: e4b71580-f084-11e3-959e-273aa801dd81 
Driver info: org.openqa.selenium.phantomjs.PhantomJSDriver 
Capabilities [{platform=XP, acceptSslCerts=false, javascriptEnabled=true, browserName=phantomjs, rotatable=false, driverVersion=1.1.0, locationContextEnabled=false, version=1.9.7, cssSelectorsEnabled=true, databaseEnabled=false, handlesAlerts=false, browserConnectionEnabled=false, webStorageEnabled=false, nativeEvents=true, proxy={proxyType=direct}, applicationCacheEnabled=false, driverName=ghostdriver, takesScreenshot=true}] 
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) 
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source) 
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source) 
    at java.lang.reflect.Constructor.newInstance(Unknown Source) 
    at org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:204) 
    at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:156) 
    at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:600) 
    at org.openqa.selenium.remote.RemoteWebElement.execute(RemoteWebElement.java:268) 
    at org.openqa.selenium.remote.RemoteWebElement.clear(RemoteWebElement.java:113) 
    at com.example.tests.Creazione.testCreazione(Creazione.java:59) 
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) 
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) 
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) 
    at java.lang.reflect.Method.invoke(Unknown Source) 
    at junit.framework.TestCase.runTest(TestCase.java:176) 
    at junit.framework.TestCase.runBare(TestCase.java:141) 
    at junit.framework.TestResult$1.protect(TestResult.java:122) 
    at junit.framework.TestResult.runProtected(TestResult.java:142) 
    at junit.framework.TestResult.run(TestResult.java:125) 
    at junit.framework.TestCase.run(TestCase.java:129) 
    at junit.framework.TestSuite.runTest(TestSuite.java:255) 
    at junit.framework.TestSuite.run(TestSuite.java:250) 
    at org.junit.internal.runners.JUnit38ClassRunner.run(JUnit38ClassRunner.java:84) 
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50) 
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38) 
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467) 
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683) 
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390) 
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197) 
Caused by: org.openqa.selenium.remote.ScreenshotException: Screen shot has been taken 
Build info: version: '2.42.1', revision: '68b415a', time: '2014-05-29 16:17:18' 
System info: host: 'Silvio-Acer', ip: '10.10.1.122', os.name: 'Windows 7', os.arch: 'x86', os.version: '6.1', java.version: '1.7.0_55' 
Driver info: driver.version: RemoteWebDriver 
    at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:136) 
    ... 23 more 
Caused by: org.openqa.selenium.remote.ErrorHandler$UnknownServerException: {"errorMessage":"Element is not currently interactable and may not be manipulated","request":{"headers":{"Accept-Encoding":"gzip,deflate","Connection":"Keep-Alive","Content-Length":"27","Content-Type":"application/json; charset=utf-8","Host":"localhost:20497","User-Agent":"Apache-HttpClient/4.3.2 (java 1.5)"},"httpVersion":"1n.1","method":"POST","post":"{\"id\":\":wdc:1402393987914\"}","url":"/clear","urlParsed":{"anchor":"","query":"","file":"clear","directory":"/","path":"/clear","relative":"/clear","port":"","host":"","password":"","user":"","userInfo":"","authority":"","protocol":"","source":"/clear","queryKey":{},"chunks":["clear"]},"urlOriginal":"/session/e4b71580-f084-11e3-959e-273aa801dd81/element/%3Awdc%3A1402393987914/clear"}} 
Build info: version: '2.42.1', revision: '68b415a', time: '2014-05-29 16:17:18' 
System info: host: 'Silvio-Acer', ip: '10.10.1.122', os.name: 'Windows 7', os.arch: 'x86',  os.version: '6.1', java.version: '1.7.0_55' 
    Driver info: driver.version: unknow 

我已經加入了phantomjs.exe到Windows路徑,增加外部庫ghostdriver.jar,但沒有...

這就像兩天我試圖使其工作...

+0

它在另一個瀏覽器中工作嗎?有一個網站或HTML,我們可以看看? – SiKing

回答

25

試試這個,它爲我工作

DesiredCapabilities caps = new DesiredCapabilities(); 
caps.setJavascriptEnabled(true);     
caps.setCapability("takesScreenshot", true); 
caps.setCapability(
         PhantomJSDriverService.PHANTOMJS_EXECUTABLE_PATH_PROPERTY, 
         "your custom path\\phantomjs.exe" 
        ); 
WebDriver driver = new PhantomJSDriver(caps); 

然後將它們的其餘的都是similar..and請請評論你的觀察,有一個偉大的日子:)

+0

這一個適合我的工作。 – user2186465

3

我跟你面臨同樣的問題。我可以使用與FirefoxDriver相同的代碼,但是當我將其更改爲PhantomJSDriver時,它崩潰了。

你可以試試FirefoxDriver而不是PhantomJSDriver嗎?只是改變driver = new FirefoxDriver()

其實如果我修改由硒提供的示例代碼,更改firefox驅動器phantonjs驅動程序,它工作正常。不知道使用phantomjs有什麼問題。

import org.openqa.selenium.By; 
import org.openqa.selenium.WebDriver; 
import org.openqa.selenium.WebElement; 
import org.openqa.selenium.phantomjs.PhantomJSDriver; 
import org.openqa.selenium.support.ui.ExpectedCondition; 
import org.openqa.selenium.support.ui.WebDriverWait; 

public class Selenium2Example { 
    public static void main(String[] args) { 
     // Create a new instance of the Firefox driver 
     // Notice that the remainder of the code relies on the interface, 
     // not the implementation. 
     System.setProperty("phantomjs.binary.path", System.getProperty("user.dir")+"/phantomjs"); 
     WebDriver driver = new PhantomJSDriver(); 
     // And now use this to visit Google 
     driver.get("http://www.google.com"); 
     // Alternatively the same thing can be done like this 
     // driver.navigate().to("http://www.google.com"); 

     // Find the text input element by its name 
     WebElement element = driver.findElement(By.name("q")); 

     // Enter something to search for 
     element.sendKeys("Cheese!"); 

     // Now submit the form. WebDriver will find the form for us from the element 
     element.submit(); 

     // Check the title of the page 
     System.out.println("Page title is: " + driver.getTitle()); 

     // Google's search is rendered dynamically with JavaScript. 
     // Wait for the page to load, timeout after 10 seconds 
     (new WebDriverWait(driver, 10)).until(new ExpectedCondition<Boolean>() { 
      public Boolean apply(WebDriver d) { 
       return d.getTitle().toLowerCase().startsWith("cheese!"); 
      } 
     }); 

     // Should see: "cheese! - Google Search" 
     System.out.println("Page title is: " + driver.getTitle()); 

     //Close the browser 
     driver.quit(); 
    } 
} 
0

下載最新的selenium java綁定 - 2.45。然後從你的圖書館中刪除2.44(或任何你使用的)。

然後在您的代碼如下:

import org.openqa.selenium.phantomjs.PhantomJSDriver; 
import org.openqa.selenium.phantomjs.PhantomJSDriverService; 

public void setUp() throws Exception { 

DesiredCapabilities DesireCaps = new DesiredCapabilities(); 
DesireCaps.setCapability(PhantomJSDriverService.PHANTOMJS_EXECUTABLE_PATH_PROPERTY, "C://phantomjs.exe"); 
WebDriver driver = new PhantomJSDriver(DesireCaps); 

注* .exe文件的位置可能不是你的C盤,所以你點它正是你所儲存幻象

你應該很好地追求這一點。

+0

它看起來像你有一些代碼缺失。格式化將有助於展示這一點。 – CompanyDroneFromSector7G

相關問題