Log into Gmail Using Selenium in Python

Log into gmail using Selenium in Python

Here is the Answer to your Question:

When we work with Selenium 3.4.3, geckodriver v0.17.0 and Mozilla Firefox 53.0 using Python 3.6.1, we can use either of the locators xpath or css_selector to log into our respective Gmail accounts through Gmail's signin module v2.


Using XPATH :

Here is the sample code to log into Gmail using xpath:

from selenium import webdriver
from selenium.webdriver.firefox.firefox_binary import FirefoxBinary
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait

binary = FirefoxBinary('C:\\Program Files\\Mozilla Firefox\\firefox.exe')
caps = DesiredCapabilities().FIREFOX
caps["marionette"] = True
driver = webdriver.Firefox(capabilities=caps, firefox_binary=binary, executable_path="C:\\Utility\\BrowserDrivers\\geckodriver.exe")

driver.get("https://accounts.google.com/signin")
email_phone = driver.find_element_by_xpath("//input[@id='identifierId']")
email_phone.send_keys("your_emailid_phone")
driver.find_element_by_id("identifierNext").click()
password = WebDriverWait(driver, 5).until(
EC.element_to_be_clickable((By.XPATH, "//input[@name='password']"))
)
password.send_keys("your_password")
driver.find_element_by_id("passwordNext").click()

Using CSS_SELECTOR:

Here is the sample code to log into Gmail using css_selector:

from selenium import webdriver
from selenium.webdriver.firefox.firefox_binary import FirefoxBinary
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait

binary = FirefoxBinary('C:\\Program Files\\Mozilla Firefox\\firefox.exe')
caps = DesiredCapabilities().FIREFOX
caps["marionette"] = True
driver = webdriver.Firefox(capabilities=caps, firefox_binary=binary, executable_path="C:\\Utility\\BrowserDrivers\\geckodriver.exe")

driver.get("https://accounts.google.com/signin")
email_phone = driver.find_element_by_css_selector("#identifierId")
email_phone.send_keys("your_emailid_phone")
driver.find_element_by_css_selector(".ZFr60d.CeoRYc").click()
password = WebDriverWait(driver, 5).until(
EC.element_to_be_clickable((By.CSS_SELECTOR, "input[class='whsOnd zHQkBf'][type='password']"))
)
password.send_keys("your_password")
driver.find_element_by_css_selector(".ZFr60d.CeoRYc").click()

Automating GMAIL login using Python-Selenium

You are trying to find the Passwd id of the element which is not loaded in dom yet. Try adding some delay so that the page could load.

emailElem = browser.find_element_by_id('Email')
emailElem.send_keys('MyUserName')
nextButton = browser.find_element_by_id('next')
nextButton.click()
time.sleep(1)
passwordElem = browser.find_element_by_id('Passwd')
passwordElem.send_keys('MyPassword')
signinButton = browser.find_element_by_id('signIn')
signinButton.click()

recommended method is browser.implicitly_wait(num_of_seconds) see this

Logging into Gmail using Python with detecting failed login

Updated 02-14-2021


I was able to extract this error message:

Sample Image

using this code:

signin_failure = driver.find_elements_by_xpath("//*[contains(text(),'Couldn’t sign you in')]")
if signin_failure[1].text == 'Couldn’t sign you in':
print('something went wrong')

In a normal gmail login you will get one of these two error messages:

  • Couldn’t find your Google Account
  • Wrong password. Try again or click Forgot password to reset it

The XPATH to get these error messages is:

wrong_email = driver.find_elements_by_xpath("//*[contains(text(),'Couldn’t find your Google Account')]")

wrong_password = driver.find_elements_by_xpath("//*[contains(text(),'Wrong password. Try again or click Forgot password to reset it')]")

if you want to close the browser after an error message, such as Couldn’t sign you in then add a driver.close() statement.

signin_failure = driver.find_elements_by_xpath("//*[contains(text(),'Couldn’t sign you in')]")
if signin_failure[1].text == 'Couldn’t sign you in':
print('something went wrong')
driver.close()

If you want to keep the browser open then don't use the driver.close() statement, but add this experimental_option

chrome_options.add_experimental_option("detach", True)

I was also able to throw these error messages:

signin_failure = driver.find_elements_by_xpath("//*[contains(text(),'Couldn’t sign you in')]")

# this message was throw when the next button was clicked prior to entering a username
no_input = driver.find_elements_by_xpath("//*[contains(text(),'Enter a valid email of phone number')]")

PSEUDOCODE CODE:

This is how you could do it, but you might have to adjust the code as you test.

def gmail_login(username, password):
driver = webdriver.Chrome(ChromeDriverManager().install())
try:
driver.get(r'https://accounts.google.com/signin/v2/identifier?continue=' + \
'https%3A%2F%2Fmail.google.com%2Fmail%2F&service=mail&sacu=1&rip=1' + \
'&flowName=GlifWebSignIn&flowEntry = ServiceLogin')
driver.implicitly_wait(3)

loginBox = driver.find_element_by_xpath('//*[@id ="identifierId"]')
loginBox.send_keys(username)

nextButton = driver.find_elements_by_xpath('//*[@id ="identifierNext"]')
nextButton[0].click()

wrong_email = driver.find_elements_by_xpath("//*[contains(text(),'Couldn’t find your Google Account')]")

# you need to check this slice
if wrong_email[1].text == 'Couldn’t find your Google Account':
print('something went wrong')
driver.close()

else:
passWordBox = driver.find_element_by_xpath('//*[@id ="password"]/div[1]/div / div[1]/input')
passWordBox.send_keys(password)

nextButton = driver.find_elements_by_xpath('//*[@id ="passwordNext"]')
nextButton[0].click()

wrong_password = driver.find_elements_by_xpath("//*[contains(text(),'Wrong password. Try again or click Forgot password to reset it')]")

# you need to check this slice
if wrong_password[1].text == 'Wrong password. Try again or click Forgot password to reset it':
print('something went wrong')
driver.close()

except:
driver.close()

Original post


Google forbids using automated scripts for logging into Gmail. I have tried using selenium and I get this warning.

Cannot sign-in

When I click Learn More I get this message.

Sample Image

Please note this line: Are being controlled through software automation rather than a human

Here are other question where they discuss work arounds for this Google direct login issue:

  • “This browser or app may not be secure” error while attempting to login in to Gmail account using Selenium

  • GMail is blocking login via Automation (Selenium)

Automation Google login with python and selenium shows This browser or app may be not secure

First of all don't use chrome and chromedriver. You need to use Firefox.(if not installed) Download and install Firefox. Login to Google with normal Firefox.

You need to show the Google site that you are not a robot. You can use code like this:

from selenium import webdriver
import geckodriver_autoinstaller
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities

geckodriver_autoinstaller.install()

profile = webdriver.FirefoxProfile(
'/Users/<user name>/Library/Application Support/Firefox/Profiles/xxxxx.default-release')

profile.set_preference("dom.webdriver.enabled", False)
profile.set_preference('useAutomationExtension', False)
profile.update_preferences()
desired = DesiredCapabilities.FIREFOX

driver = webdriver.Firefox(firefox_profile=profile,
desired_capabilities=desired)

This can help you find your profile location.

But, why Firefox?

Actually there is only one reason, chromedriver was coded by Google.
They can easily understand if it is a bot or not. But when we add user data with Firefox, they cannot understand if there is a bot or not.

You can fool Google like this. It worked for me too. I tried very hard to do this. Hope it will be resolved in you too.



Related Topics



Leave a reply



Submit