WebDriver PhantomJS Unable to find element, but works fine with Firefox

淺唱寂寞╮ 提交于 2019-12-06 03:36:07

问题


I have been banging my head into the wall for a long time now so I thought I would ask the "experts" why the below code would not work (entering password) with PhantomJS but works just fine with Firefox. The most disturbing of all is that one field entry (username) is successful but the second would not work at all. The page loads just fine and I have included test code to verify other components are loaded just fine.

See code below:

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();
}
}

回答1:


PhantomJS 1.x has a problem with element IDs. The site is broken, because it uses password for two elements on the page which should never happen. Simply replacing the id in the selector with the element type (input) solves it.

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



回答2:


Try the methods from this link

From my experience with WebDriver, it's usually timing issues. Call the method in above link at the beginning of your code so you can make sure everything loads before you try to find them. Or you can simply use Thread.Sleep with long enough time before finding elements.



来源:https://stackoverflow.com/questions/26742014/webdriver-phantomjs-unable-to-find-element-but-works-fine-with-firefox

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!