使用 Selenium webdriver 登录 Gmail 失败。显示密码元素未找到。
在使用 Selenium webdriver 时,我们可能会遇到 Gmail 登录失败,原因是密码元素未找到的错误。这可以通过以下列出的方法解决:
添加隐式等待 - 隐式等待用于指示 webdriver 在尝试识别当前不可用的元素时,轮询 DOM(文档对象模型)特定时间段。
隐式等待的默认值为 0。设置等待时间后,它将持续应用于整个 webdriver 对象的生命周期。如果未设置隐式等待并且元素仍然不存在于 DOM 中,则会抛出异常。
语法
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
这里,将五秒的等待时间应用于 webdriver 对象。
添加显式等待 - 显式等待用于指示 webdriver 在执行自动化脚本中的其他步骤之前,等待特定条件。
显式等待使用 WebDriverWait 类以及 expected_conditions 实现。expected_conditions 类有一组预构建的条件,可与 WebDriverWait 类一起使用。
在这里,我们可以为 Gmail 中密码字段的元素未找到错误添加 expected_condition 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{
//implicit wait of 15 seconds
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
//application launch
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();
//explicit wait
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 Auto-generated catch block
e.printStackTrace();
}
}
}
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP