我一直在我的头撞墙很长一段时间,所以我想我会问“专家”为什么下面的代码不会工作(输入密码)与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