小编典典

为什么Selenium驱动程序无法识别Facebook登录页面的ID元素?

selenium

我刚刚开始在在线课程中学习Selenium Webdriver。

因为我是测试和Java编程的初学者,所以请帮我。

我试图运行自动化代码以在Facebook登录页面中自动填写用户名。最初运行该程序已成功输出。

但是在第二次尝试时,我遇到了以下错误

org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"id","selector":"email"}

之后,我用Google搜索并找到了这个SO 问题,]复制 到我的代码中。

public class Helloworld {

   public static void main(String[] args) {

        System.setProperty("webdriver.chrome.driver","C:\\Seenu\\Selenium\\Driver"
        +"\\Chromedriver\\chromedriver.exe");
        WebDriver drive = new ChromeDriver();
        drive.get("https://www.facebook.com");
        // part copied from other SO question
        //Copied code starts here with little modification
        List<WebElement> elements = drive.findElements(By.id("email"));     
        if(elements.size() > 0)
        {
             System.out.println(elements.get(0).getText());
        }
        //Copied code ends here.
        else
        {
              elements.get(0).sendKeys("username@gmail.com");
              System.out.println("Username successfully entered");
        }
   }
}

但是,我得到这个下面的错误。

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at java.util.ArrayList.rangeCheck(Unknown Source)
at java.util.ArrayList.get(Unknown Source)
at Basic.Helloworld.main(Helloworld.java:40)

我的问题是为什么Selenium驱动程序无法识别Facebook登录页面的id元素

你们能请我解决这个问题吗?


阅读 541

收藏
2020-06-26

共1个答案

小编典典

要登录 Facebook ,可以使用以下代码块:

System.setProperty("webdriver.gecko.driver", "C:\\path\\to\\geckodriver.exe");
WebDriver driver =  new FirefoxDriver();
driver.get("https://www.facebook.com/");
driver.findElement(By.cssSelector("input#email")).sendKeys("Selenium");
driver.findElement(By.cssSelector("input[name='pass']")).sendKeys("Automation");
driver.findElement(By.cssSelector("input[value='Log In']")).click();
2020-06-26