Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Automatically Google login by selenium
mail_address = ''
password = ''
from selenium import webdriver
UA = 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:25.0) Gecko/20100101 Firefox/25.0'
PHANTOMJS_ARG = {'phantomjs.page.settings.userAgent': UA}
driver = webdriver.PhantomJS(desired_capabilities=PHANTOMJS_ARG)
url = 'https://www.google.com/accounts/Login?hl=ja&continue=http://www.google.co.jp/'
driver.get(url)
driver.find_element_by_id("Email").send_keys(mail_address)
driver.find_element_by_id("next").click()
driver.find_element_by_id("Passwd").send_keys(password)
driver.find_element_by_id("signIn").click()
@joaquindev

This comment has been minimized.

Copy link

joaquindev commented Oct 6, 2017

Is this still working? Thank you! Google has changed its login screen. Any new gist?

@memii

This comment has been minimized.

Copy link

memii commented Oct 23, 2017

Use this code below for the updated login screen. Tested and working.

driver.find_element_by_id("identifierId").send_keys(mail_address)
driver.find_element_by_id("identifierNext").click()
driver.find_element_by_name("password").send_keys(password)
driver.find_element_by_id("passwordNext").click()
@wheelerruss

This comment has been minimized.

Copy link

wheelerruss commented Oct 29, 2017

@memii - when I use this code it says element not visible

@nthakor

This comment has been minimized.

Copy link

nthakor commented Nov 13, 2017

I get this following error

Traceback (most recent call last):
  File "goog_login.py", line 13, in <module>
    driver.find_element_by_id("identifierId").send_keys(mail_address)
  File "/anaconda/envs/web_qoe/lib/python2.7/site-packages/selenium/webdriver/remote/webdriver.py", line 341, in find_element_by_id
    return self.find_element(by=By.ID, value=id_)
  File "/anaconda/envs/web_qoe/lib/python2.7/site-packages/selenium/webdriver/remote/webdriver.py", line 843, in find_element
    'value': value})['value']
  File "/anaconda/envs/web_qoe/lib/python2.7/site-packages/selenium/webdriver/remote/webdriver.py", line 308, in execute
    self.error_handler.check_response(response)
  File "/anaconda/envs/web_qoe/lib/python2.7/site-packages/selenium/webdriver/remote/errorhandler.py", line 194, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoSuchElementException: Message: {"errorMessage":"Unable to find element with id 'identifierId'","request":{"headers":{"Accept":"application/json","Accept-Encoding":"identity","Connection":"close","Content-Length":"93","Content-Type":"application/json;charset=UTF-8","Host":"127.0.0.1:58091","User-Agent":"Python http auth"},"httpVersion":"1.1","method":"POST","post":"{\"using\": \"id\", \"sessionId\": \"b10ca620-c829-11e7-82f2-2d961ffcc2a5\", \"value\": \"identifierId\"}","url":"/element","urlParsed":{"anchor":"","query":"","file":"element","directory":"/","path":"/element","relative":"/element","port":"","host":"","password":"","user":"","userInfo":"","authority":"","protocol":"","source":"/element","queryKey":{},"chunks":["element"]},"urlOriginal":"/session/b10ca620-c829-11e7-82f2-2d961ffcc2a5/element"}}
Screenshot: available via screen
@pilgrim2go

This comment has been minimized.

Copy link

pilgrim2go commented Jan 29, 2018

I got error

selenium.common.exceptions.ElementClickInterceptedException: Message: Element <div id="passwordNext" class="O0WRkf zZhnYe e3Duub C0oVfc Zp5qWd Hj2jlf dKVcQ"> is not clickable at point (781.1500244140625,377.25) because another element <div class="ANuIbb IdAqtf"> obscures it

@JosephShenton

This comment has been minimized.

Copy link

JosephShenton commented Mar 11, 2018

replace

driver.find_element_by_id("passwordNext").click()

with

element = driver.find_element_by_id('passwordNext')
driver.execute_script("arguments[0].click();", element)
@jackno

This comment has been minimized.

Copy link

jackno commented Dec 23, 2019

Updated Dec 2019 (also this script will wait until the fields have loaded)

# Find login field
login_field = WebDriverWait(driver, 10).until(
    EC.presence_of_element_located((By.ID, 'identifierId')))
login_field.send_keys('my-email')

# Click next button
driver.find_element_by_id('identifierNext').click()

# Find password field
password_field = WebDriverWait(driver, 10).until(
    EC.presence_of_element_located((By.ID, 'password')))
password_field = password_field.find_element_by_tag_name('input')
password_field.send_keys('my-password')

# Click next button
driver.find_element_by_id('passwordNext').click()
@wbf1013

This comment has been minimized.

Copy link

wbf1013 commented Dec 26, 2019

not working now , if anybody can use it ? I got some errors.
**Couldn't sign you in** This browser or app may not be secure. Try using a different browser. If you’re already using a supported browser, you can refresh your screen and try again to sign in.

@cchabanois-sfdc

This comment has been minimized.

Copy link

cchabanois-sfdc commented Dec 27, 2019

I am having the same issue. Tried both with ChromeDriver and FirefoxDriver

@FreelanceDev217

This comment has been minimized.

Copy link

FreelanceDev217 commented Jan 3, 2020

**Couldn't sign you in** This browser or app may not be secure. Try using a different browser. If you’re already using a supported browser, you can refresh your screen and try again to sign in.

Same issue here.
Maybe google changed its policy?

@kemangjaka

This comment has been minimized.

Copy link

kemangjaka commented Jan 6, 2020

Same issue here.
Does anyone solve it?

@sangminleo

This comment has been minimized.

Copy link

sangminleo commented Jan 6, 2020

Couldn't sign you in This browser or app may not be secure. Try using a different browser. If you’re already using a supported browser, you can refresh your screen and try again to sign in.

Same issue here, too...
somebody help we..

@tiago3613

This comment has been minimized.

Copy link

tiago3613 commented Jan 6, 2020

I've managed it using chromedriver

driver.find_element_by_id('identifierId').send_keys(email)
driver.find_element_by_xpath('//*[@id="identifierNext"]').click()

driver.find_element_by_css_selector("input[type=password]").send_keys(password)
driver.find_element_by_id('passwordNext').click()
@FreelanceDev217

This comment has been minimized.

Copy link

FreelanceDev217 commented Jan 6, 2020

@tiago3613 Can't be. just tested but not work. this used to work before Google didn't block login from Selenium.

@ChrinnerRomson

This comment has been minimized.

Copy link

ChrinnerRomson commented Jan 6, 2020

Not working on SafariDriver either. Does anyone know how Google checks for a WebDriver browser? Maybe there is a way to pass a certificate to Google that will allow login.

@cchabanois

This comment has been minimized.

Copy link

cchabanois commented Jan 8, 2020

I guess google now detects and blocks webdriver.
For example, there is a window.navigator.webdriver property when using webdriver (set it to true using ObjectDefine in your chrome browser and you will have the same error message, even though you don't use webdriver).
Some links that could help:
https://intoli.com/blog/not-possible-to-block-chrome-headless/
https://github.com/berstend/puppeteer-extra/tree/master/packages/puppeteer-extra-plugin-stealth
https://github.com/antoinevastel/fpscanner

I successfully set webdriver property to false using a chrome plugin (see https://intoli.com/blog/javascript-injection/) but even with webdriver property undefined, google still detects that we are using webdriver ...

@FreelanceDev217

This comment has been minimized.

Copy link

FreelanceDev217 commented Jan 8, 2020

After all, you failed again like others...

@pavelgordon

This comment has been minimized.

Copy link

pavelgordon commented Jan 8, 2020

Hey guys, same problem here. Tried to use different user agent without success.

@kemangjaka

This comment has been minimized.

Copy link

kemangjaka commented Jan 10, 2020

コメント 2020-01-11 004410

@tiago3613 Hi, Thank you for the info!
I tried to login with your url, but I got the same message...

@Narcolapser

This comment has been minimized.

Copy link

Narcolapser commented Jan 14, 2020

it would seem that however, they do it is innate to the browser being driven I ran this:

driver = webdriver.Chrome()

Which is to say, I opened the browser with selenium and nothing else, and then proceeded to login manually, still gave the error.

@Akif397

This comment has been minimized.

Copy link

Akif397 commented Jan 22, 2020

Isn't there any possible solution?

@Narcolapser

This comment has been minimized.

Copy link

Narcolapser commented Jan 23, 2020

We need to figure out a way to hide the fact that the browser is being controlled by selenium.

@jessfeliciano

This comment has been minimized.

Copy link

jessfeliciano commented Jan 25, 2020

I agree ^^^^

I've been experimenting with a few things, mostly centered around manipulating the user agent. I don't know if changing the user agent will be the solution, but this is just my starting point.

I will update this thread as I get more info and run tests.

@jessfeliciano

This comment has been minimized.

Copy link

jessfeliciano commented Jan 25, 2020

Has anyone tried updating their chromedriver to remove $cdc?

https://stackoverflow.com/questions/33225947/can-a-website-detect-when-you-are-using-selenium-with-chromedriver

I tried doing this with Vim (as outlined in the above link), but I couldn't even find $cdc in my chromedriver file. That post was created some five years ago and was tested with a much older chromedriver version, so I can only imagine how many changes they've made since that time.

I've also tried a few other things, various Chrome Options and a Firefox user agent:

'

chrome_options.add_argument("--disable-extensions")

chrome_options.add_argument("--disable-popup-blocking")

chrome_options.add_argument("--profile-directory=Default")

chrome_options.add_argument("--ignore-certificate-errors")

chrome_options.add_argument("--disable-plugins-discovery")

chrome_options.add_argument("--incognito")

chrome_options.add_argument("user_agent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.11; rv:46.0) Gecko/20100101 Firefox/46.0'")`

So no luck yet, but I'm thinking I can do a bit more with the user agent.

Edits because the code wasn't formatting correctly, smh. It's good now.

@crky14

This comment has been minimized.

Copy link

crky14 commented Feb 6, 2020

Hey, have you managed to get it working ? @jessfeliciano

@iliiliiliili

This comment has been minimized.

Copy link

iliiliiliili commented Feb 7, 2020

You can go to less secure apps settings and turn it on for your Google account, it must fix the problem.

@MetaMimic

This comment has been minimized.

Copy link

MetaMimic commented Feb 10, 2020

Having the same issue. I am able to login to Google "normally" via Selenium, using:
driver.get("https://accounts.google.com/ServiceLogin?service=mail&passive=true&rm=false&continue=https://mail.google.com/mail/&ss=1&scc=1&ltmpl=default&ltmplcache=2&emr=1&osid=1#identifier")

After that I locate the elements, fill them in and click through. All works well.
However OAuth on websites yields the same error message "This browser or app may not be secure."

@bmarv

This comment has been minimized.

Copy link

bmarv commented Feb 18, 2020

You can go to less secure apps settings and turn it on for your Google account, it must fix the problem.

unfortunately this still doesn't work. Tried this for gmail-login in chrome-headless. Regards

@iliiliiliili

This comment has been minimized.

Copy link

iliiliiliili commented Feb 18, 2020

You can go to less secure apps settings and turn it on for your Google account, it must fix the problem.

unfortunately this still doesn't work. Tried this for gmail-login in chrome-headless. Regards

Worked for me with gmail-login and PhantomJs. Maybe, try using it on the fresh account to inspect the issue?

@NexusPrOlgtm

This comment has been minimized.

Copy link

NexusPrOlgtm commented Feb 18, 2020

You can go to less secure apps settings and turn it on for your Google account, it must fix the problem.

unfortunately this still doesn't work. Tried this for gmail-login in chrome-headless. Regards

Guys check this video https://youtu.be/HkgDRRWrZKg .. @Narcolapser @jessfeliciano @FreelanceDev217 @kemangjaka @kemangjaka @sangminleo @cchabanois-sfdc @ChrinnerRomson @cchabanois @pavelgordon @crki14 @MetaMimic

@jessfeliciano

This comment has been minimized.

Copy link

jessfeliciano commented Feb 19, 2020

That YouTube video very much worked for me. I suggest using it.

Basic synopsis of the video is to visit the Stack Overflow login page and login with your Google account. Once you’ve completed that, open a new browser instance for whichever Google product you’d like to visit and now you are logged into the account.

@jessfeliciano

This comment has been minimized.

Copy link

jessfeliciano commented Feb 22, 2020

Turns out, the YouTube video fix doesn't last. After a few days of using the automation and running tests, Google has blocked my login.

I'm working through this thread to see if I can interact with an existing browser. Hoping this works.

@NexusPrOlgtm

This comment has been minimized.

Copy link

NexusPrOlgtm commented Feb 22, 2020

No need to be that page strictly... you can also login through any app where you have existing account ,for example Soundcloud,etc...Dont know why that happen but for me this works a kod of days.I am also turned on "Allow less se cure app to login"

@jessfeliciano

This comment has been minimized.

Copy link

jessfeliciano commented Feb 22, 2020

Hmm interesting that you’ve not had any issues then. I have the allow less secure apps to login enabled as well. Might do a bit of tinkering and at the very least just use a different webpage, probably SoundCloud, like you said in the meantime.

Do you add any cookies to your browser to mask the automation?

@IcyFrogs

This comment has been minimized.

Copy link

IcyFrogs commented Feb 24, 2020

Anyone found a bloody solution for this yet? Tried fricking everything....
Turning on less secure apps doesn't do s***
Setting the user agent doesn't do s***
Downgrading to chrome 78 doesn't do s***
What I'm trying to do is login to youtube with Selenium (chromedriver)

@jessfeliciano

This comment has been minimized.

Copy link

jessfeliciano commented Feb 24, 2020

@vovanluan

This comment has been minimized.

Copy link

vovanluan commented Feb 28, 2020

The fix in the aboved video doesnt work anymore.

@NexusPrOlgtm

This comment has been minimized.

Copy link

NexusPrOlgtm commented Feb 28, 2020

Then how the hell still works for me https://prnt.sc/r8t97r /// http://prntscr.com/r8tccb >.<
Try to use any app where you connect with googe... i am even turned off option "Allow less secure apps", and still is possible to login because this goes through apps which google flag as safe :)

@jessfeliciano

This comment has been minimized.

Copy link

jessfeliciano commented Feb 28, 2020

@NexusPrOlgtm

This comment has been minimized.

Copy link

NexusPrOlgtm commented Feb 28, 2020

Well it depend what i need... for example if i want to make SoundcloudFollow automation then login to Soudcloud, if its something with Instagram then Instagram,Pintrest ...and so on....i have many accounts connected with google so i can choose any of them.
Each page with these buttons (for example http://prntscr.com/r94uad /// http://prntscr.com/r94uy7 /// http://prntscr.com/r94vtn ) is good for login.

@sainad2222

This comment has been minimized.

Copy link

sainad2222 commented Mar 5, 2020

Any update on how to bypass?

@AsmaaFailat

This comment has been minimized.

Copy link

AsmaaFailat commented Mar 10, 2020

did you find solution for this issue please help ? I want the gmail to login through chrome automation extension
image

@vovanluan

This comment has been minimized.

Copy link

vovanluan commented Mar 12, 2020

I wrote a javascript file to login. I made two tests:

  1. Open chrome via cmd and use chromedriver to connect to this existing chrome process, then run the javascript file in this chrome by selenium.
    Result: "This browser or app may not be secure"
  2. Open chrome via cmd, then paste content of javascript file into console to login,
    Result: Login successfully.
    What's the differences? I dont use any selenium functions like sendkeys, click, etc... All is done via the code in js file. The chrome processes in two cases opened via cmd not via selenium.
@kemangjaka

This comment has been minimized.

Copy link

kemangjaka commented Mar 26, 2020

Does anyone find a solution for logging in?

@kemangjaka

This comment has been minimized.

Copy link

kemangjaka commented Mar 26, 2020

In my case, first I go to some website that can log in via target google account, and type e-mail and password.
Then, move to the google service, and it worked.

@GianellaVezzoni

This comment has been minimized.

Copy link

GianellaVezzoni commented Mar 28, 2020

Hi everybody! Really nice to meet you.
I'm working on my automation in Gmail Login too, and i'm having the same issue. Can anyone tell me if exist a solution for that problem?

@NexusPrOlgtm

This comment has been minimized.

Copy link

NexusPrOlgtm commented Mar 29, 2020

https://youtu.be/HkgDRRWrZKg @kemangjaka @GianellaVezzoni @AsmaaFailat ...try this metod with login through app connected to Google.

@hufflehuffle

This comment has been minimized.

Copy link

hufflehuffle commented Apr 10, 2020

I created an anonymous login to post this because I don't want to be blocked :-)

It seems this is not a detection of WebDriver. I assume it has to do with the clean profile the browser creates and that it is failing to accept some cookies or something.

I instruct Chrome to use my regular profile. This solved my problem.

    Dim sc As New WebDriver
   
    sc.AddArgument "user-data-dir=C:/Users/user_name/AppData/Local/Google/Chrome/User Data"
    
    sc.start "Chrome"
    sc.Get "https://search.google.com/search-console?resource_id=https://www." & baseURL
@camchis

This comment has been minimized.

Copy link

camchis commented May 21, 2020

Has anyone tried using something other than Selenium?

@iamuv2000

This comment has been minimized.

Copy link

iamuv2000 commented Jun 8, 2020

I have figured out how to avoid the "Secure login" issue. Open the automated browser and manually create an account in the automated window itself. This account can log in inside the automated browser. Give it a shot

@Brandawg93

This comment has been minimized.

Copy link

Brandawg93 commented Jun 8, 2020

I have successfully bypassed the "This browser may not be secure" message in Node.js by using puppeteer, puppeteer-extra, and puppeteer-extra-plugin-stealth. The key is to use version 2.4.5 of the stealth plugin and not the latest release. Here is the relevant code:

import puppeteer from 'puppeteer-extra';
import pluginStealth from 'puppeteer-extra-plugin-stealth';
import * as readline from 'readline';

puppeteer.use(pluginStealth());

const headless = !process.argv.includes('-h');
const prompt = (query: string, hidden = false): Promise<string> =>
  new Promise((resolve, reject) => {
    const rl = readline.createInterface({
      input: process.stdin,
      output: process.stdout,
    });
    try {
      if (hidden) {
        const stdin = process.openStdin();
        process.stdin.on('data', (char: string) => {
          char = char + '';
          switch (char) {
            case '\n':
            case '\r':
            case '\u0004':
              stdin.pause();
              break;
            default:
              process.stdout.clearLine(0);
              readline.cursorTo(process.stdout, 0);
              process.stdout.write(query + Array(rl.line.length + 1).join('*'));
              break;
          }
        });
      }
      rl.question(query, (value) => {
        resolve(value);
        rl.close();
      });
    } catch (err) {
      reject(err);
    }
  });

puppeteer.launch({ headless: headless }).then(async (browser: any) => {
  console.log('Opening chromium browser...');
  const page = await browser.newPage();
  const pages = await browser.pages();
  pages[0].close();
  await page.goto('https://home.nest.com', { waitUntil: 'networkidle2' });
  if (headless) {
    await page.waitForSelector('button[data-test="google-button-login"]');
    await page.waitFor(1000);
    await page.click('button[data-test="google-button-login"]');

    await page.waitForSelector('#identifierId');
    let badInput = true;
    while (badInput) {
      const email = await prompt('Email or phone: ');
      await page.type('#identifierId', email);
      await page.waitFor(1000);
      await page.keyboard.press('Enter');
      await page.waitFor(1000);
      badInput = await page.evaluate(() => document.querySelector('#identifierId[aria-invalid="true"]') !== null);
      if (badInput) {
        console.log('Incorrect email or phone. Please try again.');
        await page.click('#identifierId', { clickCount: 3 });
      }
    }
    const password = await prompt('Enter your password: ', true);
    console.log('Finishing up...');
    await page.type('input[type="password"]', password);
    await page.waitFor(1000);
    await page.keyboard.press('Enter');
  }
});

You can view the rest of the code on the Github for homebridge-nest-cam.

Edit: I've cleaned this up and added it to a Github gist.

@ProblemSo

This comment has been minimized.

Copy link

ProblemSo commented Jun 9, 2020

Ich habe die Lösung gefunden (ich hoffe ihr könnt mich auf Deutsch verstehen : ) ). Der Trick ist folgender: Ihr öffnet die folgende Seite mit Selenium hier der Link
Mit diesem Link versucht ihr euch nämlich mit Google bei stackauth.com anzumelden. Jetzt müsst ihr euch nur noch durch die Anmeldung navigieren und nach dem Abschluss einfach auf eure gewünschte Website....
`from selenium import webdriver
import os
from selenium import webdriver
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
import time
from selenium.webdriver.common.keys import Keys
import random

driver = webdriver.Chrome('')
driver.get('https://accounts.google.com/signin/oauth/identifier?client_id=717762328687-iludtf96g1hinl76e4lc1b9a82g457nn.apps.googleusercontent.com&scope=profile%20email&redirect_uri=https%3A%2F%2Fstackauth.com%2Fauth%2Foauth2%2Fgoogle&state=%7B%22sid%22%3A1%2C%22st%22%3A%2259%3A3%3ABBC%2C16%3A9b15b0994c6df9fc%2C10%3A1591711286%2C16%3A66b338ce162d6599%2Ca78a0c663f0beb12c0559379b61a9f5d62868c4fbd2f00e46a86ac26796507a1%22%2C%22cdl%22%3Anull%2C%22cid%22%3A%22717762328687-iludtf96g1hinl76e4lc1b9a82g457nn.apps.googleusercontent.com%22%2C%22k%22%3A%22Google%22%2C%22ses%22%3A%22921f8f04441041069683cc2377152422%22%7D&response_type=code&o2v=1&as=NCQvtBXI4prkLLDbn4Re0w&flowName=GeneralOAuthFlow')

time.sleep(5)
driver.find_element_by_xpath('/html/body/div[1]/div[1]/div[2]/div/div[2]/div/div/div[2]/div/div[1]/div/form/span/section/div/div/div[1]/div/div[1]/div/div[1]/input').send_keys('YourEmail')
driver.find_element_by_xpath( '/html/body/div[1]/div[1]/div[2]/div/div[2]/div/div/div[2]/div/div[2]/div/div[1]/div/div/span/span' ).click()

time.sleep(5)
driver.find_element_by_name( 'password' ).send_keys( "YourPassword" )
driver.find_element_by_xpath( '/html/body/div[1]/div[1]/div[2]/div/div[2]/div/div/div[2]/div/div[2]/div/div[1]/div/div/span/span' ).click()

time.sleep(5)
print('Anmeldung bei Google erfollgt')
driver.get('https://www.google.de/?hl=de')
`

@Testerscafe13

This comment has been minimized.

Copy link

Testerscafe13 commented Jun 30, 2020

Selenium with Java

Finally I did it but its little tricky and achieve the following scenario
-> Login with gmail (Google Chrome Version 83)
-> Compose an email
-> select different label
-> send it to myself
-> and verified the mail received

Please let me know if help is need to complete the task

No need to create new account, just use your existing one ....

Thank you

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.