How to automate gmail login process using selenium webdriver in java

+10 votes

Announcement! Career Guide 2019 is out now. Explore careers to become a Big Data Developer or Architect!

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.WebElement;

import org.openqa.selenium.firefox.FirefoxDriver;

import org.openqa.selenium.support.ui.ExpectedConditions;

import org.openqa.selenium.support.ui.WebDriverWait;


public class GmailDemo {

    public static void main(String[] args) {

            WebDriver driver = new FirefoxDriver();

            driver.manage().window().maximize();

            String url = "https://accounts.google.com/signin";

            driver.get(url);

            driver.findElement(By.id("identifierId")).sendKeys("raj8805"); 

            //driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);      

            WebDriverWait wait=new WebDriverWait(driver, 20);               

            driver.findElement(By.xpath("//span[@class='RveJvd snByac']")).click();         

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

            driver.findElement(By.xpath("//input[@class='whsOnd zHQkBf']")).sendKeys("asassassa");             

            driver.findElement(By.xpath("//span[@class='RveJvd snByac']")).click(); 

    }  

}

The problem is that, after mail id page, my password is getting written in the id box option & the server redirects to next password page. I want to ask, what should I do so that my password would be entered only in password page?

Apr 24, 2018 in Selenium by Martin
• 4,320 points
197,281 views
It works PERFECT!!!!!!!!!!!!!!!!!!!!!!

Thanks
if you are looking for to read the gmail message/mail, it is easy to do it with google api's which can help to read/search/compose/edit emails.

https://developers.google.com/gmail/api/guides/
Hi Vishwa, I agree with you. Google Api helps in reading or searching for emails in gmail.
WebDriver driver = null;

try {

System.setProperty("webdriver.chrome.driver", "path of chrome driver");

}

catch(Exception ex) {

ex.printStackTrace();

System.out.println("Error in getting driver -> "+ex.getLocalizedMessage());

}

driver = new ChromeDriver();

driver.get("https://accounts.google.com/signin");

driver.manage().window().maximize();

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

driver.findElement(By.id("identifierId")).sendKeys("your email", Keys.ENTER);

WebDriverWait wait=new WebDriverWait(driver, 5);               

        //driver.findElement(By.xpath("//span[@class='CwaK9']")).click();         

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

        WebElement element = wait.until(

            ExpectedConditions.visibilityOfElementLocated(By.id("password")));

        driver.findElement(By.xpath("//input[@name='password']")).sendKeys("your password");

        

        driver.findElement(By.xpath("//span[@class='RveJvd snByac']")).click();
бланк изготовление, где заказать дешево?

17 answers to this question.

+4 votes
Best answer

Check the below code:

Here is the working code block to login into your Gmail account through a valid set of credentials-

    System.setProperty("webdriver.gecko.driver","C:\\your_directory\\geckodriver.exe");

    WebDriver driver = new FirefoxDriver();

    driver.manage().window().maximize();

    String url = "https://accounts.google.com/signin";

    driver.get(url);

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

    WebElement email_phone = driver.findElement(By.xpath("//input[@id='identifierId']"));

    email_phone.sendKeys("your_email_phone");

    driver.findElement(By.id("identifierNext")).click();

    WebElement password = driver.findElement(By.xpath("//input[@name='password']"));

    WebDriverWait wait = new WebDriverWait(driver, 20);

    wait.until(ExpectedConditions.elementToBeClickable(password));

    password.sendKeys("your_password");

    driver.findElement(By.id("passwordNext")).click();
answered Apr 24, 2018 by Vardy
• 2,360 points

selected Dec 6, 2018 by Vardhan
this same code gives exception: ElementNotInteractableException due to password field is hidden
Yes....I have myself noticed this problem at times.
Thanksss you r great.. code works perfectly..
Glad it helped :)
I have wrote same code in interview but still they rejected me. Is there any other way to write the more effective code
Yeah.. it's working for me as well.. Thanks
There can certainly be other ways of tweaking the code to achieve the same thing. This is one of the most straight forward ways, and there shouldn't be any reason to reject you for this :(
Hi,

After running the above code it is keep on showing the loading screen.Not opening any page.
@Suman, can you please share your console logs here. The logs will help us understand where the program is malfunctioning.

Besides, are you sure that you're not confusing WebDriver's wait time with browser's page load time? (or till the time when the elements are loaded on the page)
I am also getting the same error:
ElementNotInteractableException due to password field is hidden

Hey @Shashank, you can try this code let me know if it works 

import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class GmailLogin {
   public static void main(String[] args) throws InterruptedException   
   {
      System.setProperty("webdriver.chrome.driver","C:\\Users\\priyj_kumar\\Downloads\\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      driver.get("https://www.gmail.com");
      driver.findElement(By.id("identifierId")).sendKeys("priyajkumart",Keys.ENTER);
      Thread.sleep(3000);
      driver.findElement(By.name("password")).sendKeys("PASSWORD",Keys.ENTER);
      Thread.sleep(4000);
      driver.close();
   }
}
it works for me thanks a lot man!
this could support jdk 1.8 versions or not  especially sendKeys....help me because not working
Hey @aman, could you please post the error you are getting?
+3 votes

Below code worked fine for me (just change the email id n password from your end):-

package GmailDemos;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class gmailLogin {
public static void main(String[] args) {
// TODO Auto-generated method stub
gmailLogin obj = new gmailLogin();
obj.loginBrowser();
}
public void loginBrowser() {
System.setProperty("webdriver.firefox.marionette","D:\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.manage().deleteAllCookies();
driver.manage().timeouts().pageLoadTimeout(15,TimeUnit.SECONDS);
driver.manage().timeouts().implicitlyWait(10,TimeUnit.SECONDS);
driver.get("http://www.gmail.com");
driver.findElement(By.id("identifierId")).sendKeys("abc@gmail.com");
driver.findElement(By.xpath(".//*[@id='identifierNext']/div[2]")).click();
driver.findElement(By.xpath(".//*[@id='password']/div[1]/div/div[1]/input")).sendKeys("password");
driver.findElement(By.xpath(".//*[@id='passwordNext']/div[2]")).click();
}
}
answered Jun 29, 2018 by Meci Matt
• 9,460 points

edited Jul 3, 2018 by Meci Matt
yes, is it working but some changes on next button xpath
Thank you
so what exactly is the difference?
Thank you Akshay. What is the change in XPath for next button?
+3 votes

As far as I could understand your problem you are trying to enter the email id ,press on forgot
password and enter the recovery email. So, here the issue which you are facing is that your xpath
which identifies the email id uniquely is same for the recovery email id too. So, putting implicit
wait would not solve your issue. Since the xpath for both are same and also since the speed of
selenium is much more faster than your internet so before going to the recovery page your
normal id is being detected.

To overcome such problems you can use two different xpath , or, you can also use explicit wait.

Your code after changing the xpath:

import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.WebDriverWait;
public class css
{
public static WebDriver driver=null;
public static WebDriverWait wait=null;
public static void main(String[] args)
{
System.setProperty("webdriver.chrome.driver","D:\\SeleniumFiles\\Selenium\\Drivers\\c
hromedriver.exe");

driver = new ChromeDriver();
wait = new WebDriverWait(driver, 60);

String url = "https://accounts.google.com/signin";
driver.get(url);
driver.findElement(By.xpath("//input[@id='identifierId'][@class='whsOnd
zHQkBf'][@type='email']")).sendKeys("raj8805");
driver.findElement(By.xpath("//span[@class='RveJvd snByac']")).click();
driver.manage().timeouts().implicitlyWait(50, TimeUnit.SECONDS);
driver.findElement(By.xpath("//input[@id='recoveryIdentifierId']")).sendKeys("asassas
sa");

driver.findElement(By.xpath("//*[@id=\"queryPhoneNext\"]/content/span")).click();
}

}

Your code after using explicit wait:

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class css
{
public static WebDriver driver=null;
public static WebDriverWait wait=null;
public static void main(String[] args)
{
System.setProperty("webdriver.chrome.driver","D:\\SeleniumFiles\\Selenium\\Drivers\\c
hromedriver.exe");

driver = new ChromeDriver();
wait = new WebDriverWait(driver, 60);
String url = "https://accounts.google.com/signin";

driver.get(url);
driver.findElement(By.id("identifierId")).sendKeys("raj8805");
driver.findElement(By.xpath("//span[@class='RveJvd snByac']")).click();
wait = new WebDriverWait(driver, 20);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//h1[text()='Find
your email']")));
System.out.println("Located");
driver.findElement(By.xpath("//input[@class='whsOnd
zHQkBf']")).sendKeys("asassassa");

driver.findElement(By.xpath("//span[@class='RveJvd snByac']")).click();
}

}
answered Jul 22, 2018 by king_kenny
• 3,710 points
+3 votes
import time
from selenium import webdriver
from selenium.webdriver.common.keys import Keys


driver= webdriver.Firefox()
#driver= webdriver.Chrome("E:\QA\Resource\WEBDRIVER\chromedriverserver\chromedriver.exe")
driver.get("http://mail.google.com")

emailid=driver.find_element_by_id("Email")
emailid.send_keys("username")

passw=driver.find_element_by_id("Passwd")
passw.send_keys("password")

signin=driver.find_element_by_id("signIn")
signin.click()

time.sleep(10)

driver.switch_to_frame('canvas_frame')

sentmail= driver.find_element_by_link_text('Sent Mail')
sentmail.click()

time.sleep(10)

sentmail= driver.find_element_by_link_text('Your Name')
sentmail.click()

lout= driver.find_element_by_link_text('Sign out')
lout.click()
answered Aug 24, 2018 by Omkar
• 69,230 points
+3 votes

I don't have lots of knowledge but yes I told you the seven basic steps of Selenium tests:

  • Create a WebDriver instance
  • Navigate to a Web page.
  • Locate an HTML element on the Web page.
  • Perform an action on an HTML element.
  • Anticipate the browser response to the action.
  • Run tests and record test results using a test framework.
  • Conclude the test.

Thanks! 

answered Sep 28, 2018 by emma smith
• 200 points

edited Sep 28, 2018 by Vardhan
Spot on with that annwer!
+1 vote
You can view the github project for the same:-

https://gist.github.com/qustosh/8451767
answered Nov 13, 2018 by Jino
• 5,820 points
+1 vote
answered Nov 13, 2018 by Vishal
+1 vote
You can read this blog and follow the steps given here :

https://crossbrowsertesting.com/blog/test-automation/automate-login-with-selenium/
answered Nov 13, 2018 by Nabarupa
+2 votes
package mypackage;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.WebDriverWait;
import java.util.List;
import org.openqa.selenium.firefox.*;
import java.util.concurrent.*;

public class myclass {

public static void main(String[] args) {

//initialize Chrome driver
System.setProperty("webdriver.chrome.driver", "C:\\selenium-java-2.35.0\\chromedriver_win32_2.2\\chromedriver.exe");
WebDriver driver = new ChromeDriver();

//Open gmail
driver.get("http://www.gmail.com");

// Enter userd id
WebElement element = driver.findElement(By.id("Email"));
element.sendKeys("xyz@gmail.com");

//wait 5 secs for userid to be entered
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);

//Enter Password
WebElement element1 = driver.findElement(By.id("Passwd"));
element1.sendKeys("Password");

//Submit button
element.submit();

WebElement myDynamicElement = (new WebDriverWait(driver, 15)).until(ExpectedConditions.presenceOfElementLocated(By.id("gbg4")));
driver.findElement(By.id("gbg4")).click();

//press signout button
driver.findElement(By.id("gb_71")).click();
}
}

Try this, hope it help :)

answered Nov 13, 2018 by Ali
• 11,360 points
+2 votes
Hey @martin, You'll need an email client to handle mail requests in windows.
answered Nov 13, 2018 by Kalgi
• 52,360 points
0 votes

You can use the following code to automate the process of login in Gmail.

System.setProperty("webdriver.chrome.driver","C:\\Your path\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("https://www.gmail.com");
driver.findElement(By.id("identifierId")).sendKeys("username");
driver.findElement(By.className("CwaK9")).click();
driver.findElement(By.name("password")).sendKeys("mypassword");
driver.findElement(By.className("CwaK9")).click();

Hope this helps.

answered Dec 20, 2018 by Nabarupa

in this line of code 

driver.findElement(By.className("CwaK9")).click();

"CwaK9" what it actually denotes 

"CwaK9" is the class name of an element on the page.  To click on that element, this command is used. 

+1 vote
public class Gmail
{

public static void main(String[] args) throws Exception
    
{
        
System.setProperty("webdriver.chrome.driver","D:\\nexus 5x backup\\Eclipse_2\\eclipse\\chromedriver.exe" );
        
WebDriver wd=new ChromeDriver();
        
wd.get("https://accounts.google.com/ServiceLogin/identifier?service=mail&passive=true&rm=false&continue=https%3A%2F%2Fmail.google.com%2Fmail%2F&ss=1&scc=1&ltmpl=default&ltmplcache=2&emr=1&osid=1&flowName=GlifWebSignIn&flowEntry=AddSession");//gmail sign in link
        
wd.manage().window().maximize();//for maximizing window
        
wd.findElement(By.id("identifierId")).sendKeys("");//enter username
        
Thread.sleep(2000);
        
wd.findElement(By.xpath("//*[@id=\"identifierNext\"]/content/span\r\n" + "")).click();//relative xpath for clicking next button
        
Thread.sleep(2000);
        
wd.findElement(By.name("password")).sendKeys("");//enter password
        
Thread.sleep(2000);
        
wd.findElement(By.xpath("//*[@id=\"passwordNext\"]/content/span")).click();//relative xpath for clicking next button
        
Thread.sleep(2000);

wd.findElement(By.linkText("Inbox")).click();//click on Inbox

Thread.sleep(2000);

wd.findElement(By.linkText("Starred")).click();//click on Starred

Thread.sleep(2000);

wd.findElement(By.linkText("Snoozed")).click();//click on Snoozed

Thread.sleep(2000);

wd.findElement(By.linkText("Important")).click();//click on Important

Thread.sleep(2000);

wd.findElement(By.linkText("Sent")).click();//click on Sent

Thread.sleep(2000);

wd.findElement(By.linkText("Drafts")).click();//click on Drafts

Thread.sleep(2000);
    
wd.findElement(By.cssSelector("a.gb_b.gb_hb.gb_R")).click();// Click on the image icon present in the top right navigational Bar
        
Thread.sleep(2000);
        
wd.findElement(By.id("gb_71")).click();//Click on 'Logout' Button
    }

}
answered Feb 2, 2019 by pratik koli
Hey @pratik Koli you can do the same without waiting to click on next button
Yes we have to remove thread value so without waiting we can able to login to Gmail more faster.
What do you mean by thread value here?
Thread.sleep(2000);// this value

okay. have you tried this? this looks more comfortable though the work is same but look more compact. What do you say?

import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class GmailLogin {
   public static void main(String[] args) throws InterruptedException   
   {
      System.setProperty("webdriver.chrome.driver","C:\\Users\\priyj_kumar\\Downloads\\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      driver.get("https://www.gmail.com");
      driver.findElement(By.id("identifierId")).sendKeys("priyajkumart",Keys.ENTER);
      Thread.sleep(3000);
      driver.findElement(By.name("password")).sendKeys("PASSWORD",Keys.ENTER);
      Thread.sleep(4000);
      driver.close();
   }
}
Ok I'll try.thanks for the above script.
@Pratik this doesn't give you the logout option rest all works fine. Do let me know as what is your view for the above code and it worked for you or not.
Okay I'll try and let you know ASAP.

Hey @Pratik Koli! 

It looks like you are enjoying the tech-discussion at our community! To get regular updates and to be a valuable member of edureka! Community, please register with your Email ID. 

Good code... simple and working well...
0 votes
I have started working with selenium and found this question very informative. Thank you.
answered Feb 18, 2019 by Dev
• 360 points
+1 vote

It is easy to automate gmail login process and send email with attachment using selenium.

I came across this working code which contain entire flow of login , draft attachment . It is important to select correct xpath for the elements which we need to automate.

answered Aug 6, 2019 by anonymous
Hi, can you please share your code here?

As mentioned in above comment details are available at this location

http://mundrisoft.com/tech-bytes/automate-gmail-login-process-using-selenium/

0 votes
package examples;

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.chrome.ChromeDriver;

public class Gmail_Login {

public static void main(String[] args) throws Exception {

System.setProperty("webdriver.chrome.driver", "E:\\chromedriver_win32\\chromedriver.exe");

WebDriver driver= new ChromeDriver();

driver.manage().window().maximize();

driver.get("https://accounts.google.com/signin");

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

driver.findElement(By.id("identifierId")).sendKeys("mail@gmail.com");

driver.findElement(By.xpath("//span[text()='Next']")).click();

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

driver.findElement(By.xpath("//input[@name='password']")).sendKeys("test@123");

driver.findElement(By.id("passwordNext")).click();

driver.findElement(By.xpath("//a[@class='gb_D']")).click();

Thread.sleep(3000);

driver.findElement(By.xpath("/html/body/div[2]/header/div[2]/div[4]/ul[1]/li[7]/a/span[2]")).click();

Thread.sleep(3000);

driver.close();

}

}
answered Nov 9, 2019 by venkatesh
• 140 points
0 votes

Here is the working code block to login into your Gmail account through a valid set of credentials-

System.setProperty("webdriver.gecko.driver","C:\\your_directory\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.manage().window().maximize();
String url = "https://accounts.google.com/signin";
driver.get(url);
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); 
WebElement email_phone = driver.findElement(By.xpath("//input[@id='identifierId']"));
email_phone.sendKeys("your_email_phone");
driver.findElement(By.id("identifierNext")).click();
WebElement password = driver.findElement(By.xpath("//input[@name='password']"));
WebDriverWait wait = new WebDriverWait(driver, 20);
wait.until(ExpectedConditions.elementToBeClickable(password));
password.sendKeys("your_password");
driver.findElement(By.id("passwordNext")).click();

answered Dec 14, 2020 by Roshni
• 10,520 points
0 votes
How to automate gmail login process using selenium webdriver in java  | Edureka Community
[url=http://www.gw0818d72f6xxw0ri2j985y1yvqv29i0s.org/]uhvwqgixys[/url]
hvwqgixys http://www.gw0818d72f6xxw0ri2j985y1yvqv29i0s.org/
<a href="http://www.gw0818d72f6xxw0ri2j985y1yvqv29i0s.org/">ahvwqgixys</a>
answered May 13, 2021 by hvwqgixys

Related Questions In Selenium

+1 vote
1 answer

How can I automate the process of adding iPhone to cart in Flipkart using Selenium(java),Page Object Model and TestNG? Also validate if product is added and available in cart?

Hey check this https://www.edureka.co/community/47160/automate-purchase-adding-book-cart-flipkart-using-selenium? It deals with a similar ...READ MORE

answered Jan 13, 2020 in Selenium by Karan
• 19,610 points
8,187 views
+1 vote
1 answer

How to automate instagram login page using java in selenium?

Try the following: package com.company; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import ...READ MORE

answered Sep 15, 2020 in Selenium by Karan
• 19,610 points
6,981 views
+1 vote
1 answer

How to handle drop downs using Selenium WebDriver in Java

First, find an XPath which will return ...READ MORE

answered Mar 27, 2018 in Selenium by nsv999
• 5,500 points
8,233 views
0 votes
2 answers

How to scroll the Page up or down in Selenium WebDriver? (using java)

JavascriptExecutor jsx = (JavascriptExecutor)driver; jsx.executeScript("window.scrollBy(0,555)", ""); or Action classes ...READ MORE

answered Sep 6, 2020 in Selenium by Sri
• 3,190 points
18,816 views
0 votes
2 answers

Finding WebDriver element with Class Name in java

The better way to handle this element ...READ MORE

answered Apr 10, 2018 in Selenium by nsv999
• 5,500 points
13,420 views
0 votes
2 answers

Problem while using InternetExplorerDriver in Selenium WebDriver

enable trusted connection  in internet explorer by ...READ MORE

answered Aug 31, 2020 in Selenium by Sri
• 3,190 points
8,995 views
0 votes
1 answer

Geo-location microphone camera pop up

To Allow or Block the notification, access using Selenium and you have to ...READ MORE

answered May 11, 2018 in Selenium by Samarpit
• 5,910 points
7,101 views
0 votes
2 answers

How to use such xpath to find web elements

xpath are two types. 1) Absolute XPath:    /html/b ...READ MORE

answered Sep 3, 2020 in Selenium by Sri
• 3,190 points
7,800 views
0 votes
1 answer

How to upload a resume to a website using selenium in python?

Use this code, this will help you: from ...READ MORE

answered Apr 20, 2018 in Selenium by Vardy
• 2,360 points
2,782 views
0 votes
1 answer

Select an item from a dropdown list using Selenium WebDriver

Use this then it will work - new ...READ MORE

answered Apr 9, 2018 in Selenium by Vardy
• 2,360 points
7,666 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP