使用 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