使用 Selenium webdriver 登录 Gmail 失败。显示未找到密码的元素。

我们在使用 Selenium webdriver 时可能会遇到 Gmail 登录失败,因为错误 - 找不到密码元素。这可以通过下面列出的方法修复 -

  • 添加隐式等待 - 应用隐式等待以指示 webdriverDOM(Document Object Model)在尝试识别当前不可用的元素时轮询特定时间量。

    隐式等待时间的默认值为 0。一旦设置了等待时间,它将在 webdriver 对象的整个生命周期中保持适用。如果未设置隐式等待并且元素仍不存在于 DOM 中,则会引发异常。

语法

driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

              此处,对 webdriver 对象应用了 5 秒的等待时间。

  • 添加显式等待 - 应用显式等待以指示 webdriver 在移动到自动化脚本中的其他步骤之前等待特定条件。

    显式等待是使用 WebDriverWait 类和 expected_conditions 实现的。Expected_conditions 类具有一组与 WebDriverWait 类一起使用的预构建条件。

    在这里,我们可以为 Gmail 中密码字段的元素未找到错误添加预期条件visibilityOfElementLocated。

示例

代码实现

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.Wait;
import org.openqa.selenium.support.ui.WebDriverWait;
public class FirstAssign{
   public static void main(String[] args){
      System.setProperty("webdriver.chrome.driver", "chromedriver");
      WebDriver driver = new ChromeDriver();
      try{
         //隐式等待 15 秒
         driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
         //应用程序启动
         driver.get("http://www.gmail.com");
         WebElement e = driver.findElement
         (By.xpath("//input[@type = 'email']"));
         e.sendKeys("abc@gmail.com");
         WebElement n = driver.findElement
         (By.xpath("//button[@type = 'button']"));
         n.click();

         //显式等待
         WebDriverWait wait = new WebDriverWait(driver, 10);
         WebElement m = wait.until(
         ExpectedConditions.visibilityOfElementLocated
         (By.xpath("//input[@type = 'email']")));
         driver.findElement(By.xpath
         ("//input[@type = 'email']")).sendKeys("1234");
         n.click();
      }
      catch (Exception e)
      {
         // TODO 自动生成的 catch 块
         e.printStackTrace();
      }
   }
}