我一直在我的頭撞牆很長一段時間,所以我想我會問「專家」爲什麼下面的代碼不會工作(輸入密碼)與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();
}
}
這可能是計時問題。嘗試在每個findElement前使用Thread.Sleep(2000)並觀察行爲。如果它有效,那麼你知道它是計時問題。還有一個叫做WaitForPagetoLoad的方法。您可以在輸入元素之前調用它。 – neo 2014-11-04 18:13:59
那麼,解決了我自己的問題。似乎css選擇器不能與PhantomJS一起使用,我用.x*通過.//*[@id='password']使用,現在它可以工作。 – ucipass 2014-11-04 18:25:17
感謝neo,我實際上也是通過非常慢的eclipse調試代碼來嘗試一個。仍然不確定爲什麼CSS選擇器不工作。 – ucipass 2014-11-04 18:27:15