Vito Vito - 2 months ago 18
Java Question

How to continue to fill the data in next page by selenium?

I want to login by

Selenium
. It is divided the process into 2 pages.


  • email

  • password



Now I can input the key in first page .Then I should go next page (input password and click submit key).

However , If I just add 4 keys codes in one class ,it cannot complete the second page key input (password and submit )

I guess some code is missing between first page key input and second page key input.

public class Selenium {

/**
* @param args the command line arguments
*/
public static void main(String[] args) {



WebDriver driver;
System.setProperty("webdriver.gecko.driver", "C:\\Users\\Downloads\\geckodriver-v0.10.0-win64\\wires.exe");
driver =new FirefoxDriver();


driver.get("https://mail.google.com");
driver.findElement(By.id("Email")).sendKeys("yourEmailId");//first page
driver.findElement(By.id("next")).click();//first page

driver.findElement(By.id("Passwd")).sendKeys("yourPassword");//next page
driver.findElement(By.id("signIn")).click();//next page
}





driver.get("https://mail.google.com");
driver.findElement(By.id("Email")).sendKeys("yourEmailId");//first page
driver.findElement(By.id("next")).click();//first page


/* What code should I add here? */


driver.findElement(By.id("Passwd")).sendKeys("yourPassword");//next page
driver.findElement(By.id("signIn")).click();//next page
}

Answer

Try setting an implicit wait of maybe 10 seconds before finding this element as :-

driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.findElement(By.id("Passwd")).sendKeys("yourPassword");
driver.findElement(By.id("signIn")).click();

Or set an explicit wait. An explicit waits is code you define to wait for a certain condition to occur before proceeding further in the code. In your case, it is the visibility of the password input field.

WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement element = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("Passwd")));
element.sendKeys("yourPassword");

//Now click on sign in button 
driver.findElement(By.id("signIn")).click();//next page

Explanation: The reason selenium can't find the element is because the id of the password input field is initially Passwd-hidden. After you click on the "Next" button, Google first verifies the email address entered and then shows the password input field (by changing the id from Passwd-hidden to Passwd). So, when the password field is still hidden (i.e. Google is still verifying the email id), your webdriver starts searching for the password input field with id Passwd which is still hidden. And hence, you should wait until it becomes visible.

Comments