2014-11-04 75 views
5

我一直在我的頭撞牆很長一段時間,所以我想我會問「專家」爲什麼下面的代碼不會工作(輸入密碼)與PhantomJS但工作得很好與Firefox。最令人不安的是,一個字段輸入(用戶名)成功,但第二個根本不起作用。頁面加載得很好,我已經包含測試代碼來驗證其他組件加載得很好。WebDriver PhantomJS無法找到元素,但與火狐工作正常

見下面的代碼:

import java.io.File; 
import org.openqa.selenium.*; 
import org.openqa.selenium.firefox.FirefoxDriver; 
import org.openqa.selenium.phantomjs.PhantomJSDriver; 

public class login { 

public static void main(String[] args) { 
    WebDriver driver; 
    Boolean verbose = false; //Change to true to test it with firefox 
    String phantomPath = "../phantomjs-1.9.8-linux-i686/bin/phantomjs"; 
    String url = "https://www.britishairways.com/travel/redeem/execclub/_gf/en_us"; 

    if (verbose) { 
     driver = new FirefoxDriver(); 
     } 
    else{ 
     File file = new File(phantomPath); 
     String userAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; cs; rv:1.9.0.8) Gecko/2009032609 Firefox/3.0.8"; 
     System.setProperty("phantomjs.binary.path", file.getAbsolutePath()); 
     System.setProperty("phantomjs.page.settings.userAgent", userAgent); 

     driver = new PhantomJSDriver(); 
     } 
    driver.get(url); 
    try{ 
     driver.findElement(By.id("membershipNumber")).sendKeys("1234"); 
     System.out.println("ID input successful"); 
     if (driver.findElement(By.id("ecuserlogbutton")).isDisplayed()) { 
      System.out.println("Login Button is present"); 
     } 
     //This is where it fails with PhantomJS but work with Firefox 
     driver.findElement(By.cssSelector("#pintr > #password")).sendKeys("1234");   
     System.out.println("password input successful"); 
     } 
    catch (Exception e){ 
     System.out.print(e.getMessage()); 
     } 
    driver.close(); 
} 
} 
+0

這可能是計時問題。嘗試在每個findElement前使用Thread.Sleep(2000)並觀察行爲。如果它有效,那麼你知道它是計時問題。還有一個叫做WaitForPagetoLoad的方法。您可以在輸入元素之前調用它。 – neo 2014-11-04 18:13:59

+0

那麼,解決了我自己的問題。似乎css選擇器不能與PhantomJS一起使用,我用.x*通過.//*[@id='password']使用,現在它可以工作。 – ucipass 2014-11-04 18:25:17

+0

感謝neo,我實際上也是通過非常慢的eclipse調試代碼來嘗試一個。仍然不確定爲什麼CSS選擇器不工作。 – ucipass 2014-11-04 18:27:15

回答

8

PhantomJS 1.x在元素ID方面存在問題。該網站已損壞,因爲它使用password作爲頁面上永遠不會發生的兩個元素。只需使用元素類型(input)替換選擇器中的id即可解決此問題。

driver.findElement(By.cssSelector("#pintr > input")).sendKeys("1234"); 
+0

你搖滾先生!我沒有聲望給你一個讚許,但非常感謝!我沒有注意到密碼的重複名稱。 – ucipass 2014-11-04 19:20:02

+0

你可以[接受](http://meta.stackexchange.com/a/5235/266187)我的答案。另外,製作屏幕截圖以查看頁面上發生的情況總是很好的。 – 2014-11-04 19:21:45

+0

是的謝謝!我用屏幕截圖查看頁面,但我看到的只是空白的字段。我想我將不得不在元素ID上找到下一次查找重複項。再次感謝你的幫助!!! – ucipass 2014-11-07 17:27:08

1

Try the methods from this link

從我的經驗的webdriver,它通常是時間問題。在代碼的開始處調用上述鏈接中的方法,以便在嘗試找到它們之前確保所有內容都已加載。或者您可以在查找元素之前使用Thread.Sleep足夠長的時間。

相關問題