2014-11-04 80 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足够长的时间。

相关问题