54

I have a problem with Google login. I want to login to my account but Google says that automation drivers are not allowed to log in.

I am looking for a solution. Is it possible to get a cookie of normal Firefox/Chrome and load it into the ChromeDriver/GeckoDriver? I thought that this can be a solution. But I am not sure is it possible or not..

Looking for solutions...

enter image description here

Quick solution is using =>

var options = new ChromeOptions();
options.addArguments(@"user-data-dir=c:\Users\{username}\AppData\Local\Google\Chrome\User Data\");
Ahmet Aziz Beşli
  • 1,280
  • 3
  • 19
  • 38
  • @OrangeDog try another account. verified and old.. – Ahmet Aziz Beşli Jan 03 '21 at 20:19
  • Weirdly I'm getting this for one test gmail account but not another. Same exact security settings (insecure app access turned on, no 2FA). This is for a login with google button our app that I have automated tests for. Manually logging in in incognito mode works, but using Selenium does not. Only for one test account though. Very weird. – MattS Mar 19 '21 at 00:26
  • @MattS it is completely weird. Once I got the same problem. I couldn't fix it for a while and I thought that I can try to use different account, maybe they have a blacklist or something similar for the automated tests.. Anyway they are able to understand what type of drivers we use. I think old verified accounts (with phone number or so) are more reliable. That's why we can use the login site with them.. – Ahmet Aziz Beşli Mar 23 '21 at 11:57

13 Answers13

20

I had the same problem and found the solution for it. I am using

  1. Windows 10 Pro

  2. Chrome Version 83.0.4103.97 (Official Build) (64-bit)

  3. selenium ChromeDriver 83.0.4103.39

Some simple C# code which open google pages

var options = new ChromeOptions();
options.addArguments(@"user-data-dir=c:\Users\{username}\AppData\Local\Google\Chrome\User Data\");
IWebDriver driver = new OpenQA.Selenium.Chrome.ChromeDriver();
driver = new ChromeDriver(Directory.GetCurrentDirectory(), options);
driver.Url = "https://accounts.google.com/";
Console.ReadKey();

The core problem here you can't login when you use selenium driver, but you can use the profile which already logged to the google accounts.

You have to find where your Chrome store profile is and append it with "user-data-dir" option.

PS. Replace {username} with your real account name.

On linux the user profile is in "~/.config/google-chrome".

Benjamin Loison
  • 3,782
  • 4
  • 16
  • 33
Duke
  • 1,844
  • 2
  • 16
  • 26
  • 2
    is there a way to do this for macos – deleted Jun 02 '21 at 01:36
  • 1
    I have all of these options: - chrome_options.add_argument("--disable-web-security") - chrome_options.add_argument("--allow-running-insecure-content") - chrome_options.add_argument( "--user-data-dir=/Users/matt/Library/Application Support/Google/Chrome" ) - chrome_options.add_argument('--profile-directory=Default') and it still doesn't work for me. It still says the browser is insecure. I'm on Mac OS and Chrome version 93. – Matt Groth Sep 28 '21 at 13:28
  • 1
    @MattGroth Facing the same issue on a mac, any luck from your side? – Atul Gopinathan Oct 12 '21 at 12:27
  • 1
    @Atul I have given up on this, unfortunately. It just seems like Google is doing everything in its power to prevent us from logging in on automated browswers. I guess it's just too much of a security issue right now. – Matt Groth Oct 19 '21 at 22:29
8

This error message...

This browser or app may not be secure

...implies that the WebDriver instance was unable to authenticate the Browsing Context i.e. Browser session.


This browser or app may not be secure

This error can happen due to different factors as follows:


Solution

In these cases the respective solution would be to:

You can find a detailed discussion in Unable to sign into google with selenium automation because of "This browser or app may not be secure."


Deep Dive

However, to help protect your account, Web Browsers may not let you sign in from some browsers. Google might stop sign-ins from browsers that:

  • Doesn't support JavaScript or have Javascript turned off.
  • Have AutomationExtension or unsecure or unsupported extensions added.
  • Use automation testing frameworks.
  • Are embedded in a different application.

Solution

In these cases there are diverse solutions:

  • Use a browser that supports JavaScript:

  • Chrome

  • Safari

  • Firefox

  • Opera

  • Internet Explorer

  • Edge

  • Turn on JavaScript in Web Browsers: If you’re using a supported browser and still can’t sign in, you might need to turn on JavaScript.

  • If you still can’t sign in, it might be because you have AutomationExtension / unsecure / unsupported extensions turned on and you may need to turn off as follows:

    public class browserAppDemo 
    {
        public static void main(String[] args) throws Exception 
        {
            System.setProperty("webdriver.chrome.driver", "C:\\Utility\\BrowserDrivers\\chromedriver.exe");
            ChromeOptions options = new ChromeOptions();
            options.addArguments("start-maximized");
            options.setExperimentalOption("useAutomationExtension", false);
            options.setExperimentalOption("excludeSwitches", Collections.singletonList("enable-automation"));
            WebDriver driver =  new ChromeDriver(options); 
            driver.get("https://accounts.google.com/signin")
            new WebDriverWait(driver, 10).until(ExpectedConditions.elementToBeClickable(By.xpath("//input[@id='identifierId']"))).sendKeys("gashu");
            driver.findElement(By.id("identifierNext")).click();
            new WebDriverWait(driver, 10).until(ExpectedConditions.elementToBeClickable(By.xpath("//input[@name='password']"))).sendKeys("gashu");
            driver.findElement(By.id("passwordNext")).click();
            System.out.println(driver.getTitle());
        }
    }

Additional Considerations

Finally, some old browser versions might not be supported, so ensure that:

Benjamin Loison
  • 3,782
  • 4
  • 16
  • 33
undetected Selenium
  • 183,867
  • 41
  • 278
  • 352
  • 3
    I've seen other places that when people allow less secure apps it doesnt secure the problem. I tried it myself and it didnt work. Even though I allow it on my own google account it doesnt transfer to the window selenium opens. Do you have any other suggestions on approaches to browser automation if someone needs to access a gmail account or use google services...now that it is not easy/possibly to do with selenium – Mike Sandstrom Feb 26 '20 at 01:50
  • How to import the "Collections" in your code ?? – Noppu Mar 08 '21 at 02:35
  • Oh! I found that even with 2-factor disabled, If you have an Android device "linked" (because for example you test something in android recently with that account) Google will not get let you in, and allways ask you to open your Android and open the "app" to get the verification code. Just go to your account and unlink all androids! then try again and all will work again! – anibal Jun 03 '23 at 23:28
6

Solution without redirecting, using firefox driver, or changing any google account settings:

If you have a specific Google account you want to access, create a chrome profile with it and then load the chrome profile when using selenium:

options = webdriver.ChromeOptions()
options.add_argument("--user-data-dir=C:/Users/{userName}/AppData/Local/Google/Chrome/User Data/Profile {#}/")
driver = webdriver.Chrome("C:/bin/chromedriver.exe", chrome_options=options)

Windows:
The profile {#} in the file path above will vary so I suggest checking inside of the User Data folder which profile you want to use. For example, if you currently only have 1 chrome account there will be no Profile directory (resorts to "Default" directory) in User Data but if you create a second chrome account there will be a "Profile 1" directory in User Data.

Note that you should create a new google chrome profile to use with selenium because attempting to use a chrome profile that is already in use (opened in another chrome window) will cause an error.

Mac:
This solution may or may not work on mac but to find the chrome account folder/filepath follow the instructions in the comment left by @bfhaha

Benjamin Loison
  • 3,782
  • 4
  • 16
  • 33
Timaayy
  • 790
  • 5
  • 19
  • 2
    How can you do this for a Mac Book? – deleted Jun 02 '21 at 01:06
  • 3
    @cadd_coder This answer doesn't work for me. But I know that where is the profile. Visit `chrome://version/` There is a `Profile Path`. It tells you where is the profile. In my MacOS, it is `/Users/bfhaha/Library/Application Support/Google/Chrome/Default`. Note that you cannot see Library folder in Finder. It is hidden by default. So just use [Go] and [Go to Folder] to browser the folder. – bfhaha Jul 07 '21 at 03:31
  • Has anyone had any luck with this on OSX? – Kevin Wheeler May 26 '22 at 02:37
4

One Solution that works for me: https://stackoverflow.com/a/60328992/12939291 or https://www.youtube.com/watch?v=HkgDRRWrZKg

Short: Stackoverflow Login with Google Account with Redirect

from selenium import webdriver
from time import sleep

class Google:

    def __init__(self, username, password):

        self.driver = webdriver.Chrome('./chromedriver')
        self.driver.get('https://stackoverflow.com/users/signup?ssrc=head&returnurl=%2fusers%2fstory%2fcurrent%27')
        sleep(3)
        self.driver.find_element_by_xpath('//*[@id="openid-buttons"]/button[1]').click()
        self.driver.find_element_by_xpath('//input[@type="email"]').send_keys(username)
        self.driver.find_element_by_xpath('//*[@id="identifierNext"]').click()
        sleep(3)
        self.driver.find_element_by_xpath('//input[@type="password"]').send_keys(password)
        self.driver.find_element_by_xpath('//*[@id="passwordNext"]').click()
        sleep(2)
        self.driver.get('https://youtube.com')
        sleep(5)

username = ''
password = ''
Google(username, password)
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
3

I just tried something out that worked for me after several hours of trial and error.

Adding args: ['--disable-web-security', '--user-data-dir', '--allow-running-insecure-content' ] to my config resolved the issue.

I realized later that this was not what helped me out as I tried with a different email and it didn't work. After some observations, I figured something else out and this has been tried and tested.

Using automation:

Go to https://stackoverflow.com/users/login Select Log in with Google Strategy Enter Google username and password Login to Stackoverflow Go to https://gmail.com (or whatever Google app you want to access)

After doing this consistently for like a whole day (about 24 hours), try automating your login directly to gmail (or whatever Google app you want to access) directly... I've had at least two other people do this with success. PS - You might want to continue with the stackoverflow login until you at least get a captcha request as we all went through that phase as well.

Yinka Alabi
  • 307
  • 2
  • 3
  • 8
    after testing no luck for me and cannot login. chrome_options.add_argument() for each arg but still same security issue – uxke Oct 22 '20 at 06:09
3

This might be still open / not answered

Here is an working (28.04.2021) example in this following thread: https://stackoverflow.com/a/66308429/15784196

Use Firefox as driver. I tested his example and it did work!

charleslparker
  • 1,904
  • 1
  • 21
  • 31
Mauley
  • 39
  • 5
  • Thanks for the link, I used the selenium_stealth answer in the same thread which works perfect with Chrome! – Wouter Mar 14 '22 at 11:30
3

I solved this issue last week using following steps:

First two steps are out of your project code.

  1. Create a new user directory for Chrome browser. you can name this folder whatever you like and place it anywhere You can name this folder whatever you like and place it anywhere.

  2. Run Chrome browser in debugger mode using just created directory

cd C:\Program Files\Google\Chrome\Application

chrome.exe --remote-debuggin-port=9222 --user-data-dir="C:\localhost"

you can use any free port

You can use any free port but I followed this article: https://chromedevtools.github.io/devtools-protocol/

Browser window opens. Login manually to Google / Facebook / etc using opened window. Close the browser.

In your project:

  1. Copy chrome-user-directory you just created into 'resources' package.

enter image description here

  1. Set debugging option for Chrome driver.
     /**
     * This method is added due to Google security policies changed.
     * Now it's impossible to login in Google account via Selenium at first time.
     * We use a user data directory for Chrome where we previously logged in.
     */
    private WebDriver setWebDriver() {
        ChromeOptions options = new ChromeOptions();        
        options.addArguments("--user-data-dir=" + System.getProperty("user.dir") + "/src/main/resources/localhost");
        options.addArguments("--remote-debugging-port=9222");
        return new ChromeDriver(options);
    }
  1. Enjoy.

PS: If you have another solution without copying chrome user-directory into the project, please share it)

Benjamin Loison
  • 3,782
  • 4
  • 16
  • 33
  • I need to use different Gmail accounts. How Can I do it? – Taki Elias Aug 06 '21 at 04:30
  • @TakiElias you can just dynamically change the --user-data-dir in setWebDriver (of course, open new window). – Jaroslav Štreit Aug 14 '22 at 15:58
  • In my case I couldn't run chrome from terminal - on server thru VNC I had error: Unable to open X display. I found out which display I have: ps axu |grep -3 "X " then "export DISPLAY=:1" and voila, chrome started in my VNC window. – Jaroslav Štreit Aug 14 '22 at 16:25
3

@Mike-Fakesome on this https://gist.github.com/ikegami-yukino/51b247080976cb41fe93 thread suggest a solution that works

import undetected_chromedriver.v2 as uc
import random,time,os,sys
from selenium.webdriver.common.keys import Keys

GMAIL = '<GMAIL_HERE>'
PASSWORD = '<PASSWORD_HERE>'

chrome_options = uc.ChromeOptions()

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=DN")

driver = uc.Chrome(options=chrome_options)

driver.delete_all_cookies()

driver.get("https://accounts.google.com/o/oauth2/v2/auth/oauthchooseaccount?redirect_uri=https%3A%2F%2Fdevelopers.google.com%2Foauthplayground&prompt=consent&response_type=code&client_id=407408718192.apps.googleusercontent.com&scope=email&access_type=offline&flowName=GeneralOAuthFlow")

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(GMAIL)
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(Keys.RETURN)

time.sleep(10)

also you can use import undetected_chromedriver as uc instead of import undetected_chromedriver.v2 as uc now as well

Benjamin Loison
  • 3,782
  • 4
  • 16
  • 33
2

I found a solution ,@theycallmepix and @Yinka Albi are correct but because(i think) google blacklisted accounts that did just programatically login the first time and so later they coudn't login normally. So Basically just use different a account and go to to Stackauth or StackoverFlow. Then manually login with Google(first link your account) And then manually login in google.com and then it should work prgramaticaly

P.S. pls comment if this doesn't work

OpenSaned
  • 105
  • 1
  • 1
  • 8
1

Use the below given snippet method to Login to your Google Account.
Language: Python3
Redirect via: StackAuth (Reason explained at the end)
[Edit: You need to import the required packages. Make sure that the Automation that you do is running in Foreground, I mean, it's not minimised until you login completely. Once if the login is successful, then you can re-direct to the required website that you want.]

def login(username, password):       # Logs in the user
    driver.get('https://accounts.google.com/o/oauth2/auth/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%2'
               '259%3A3%3Abbc%2C16%3A561fd7d2e94237c0%2C10%3A1599663155%2C16%3Af18105f2b08c3ae6%2C2f06af367387a967072e3124597eeb4e36c2eff92d3eef697'
               '1d95ddb5dea5225%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%2226bafb488fcc494f92c896ee923849b6%22%7D&response_type=code&flowName=GeneralOAuthFlow')

    driver.find_element_by_name("identifier").send_keys(username)
    WebDriverWait(driver, 10).until(expected_conditions.element_to_be_clickable((By.XPATH, "//*[@id='identifierNext']/div/button/div[2]"))).click()
    driver.implicitly_wait(4)

    try:
        driver.find_element_by_name("password").send_keys(password)
        WebDriverWait(driver, 2).until(expected_conditions.element_to_be_clickable((By.XPATH, "//*[@id='passwordNext']/div/button/div[2]"))).click()
    except TimeoutException:
        print('\nUsername/Password seems to be incorrect, please re-check\nand Re-Run the program.')
        del username, password
        exit()
    except NoSuchElementException:
        print('\nUsername/Password seems to be incorrect, please re-check\nand Re-Run the program.')
        del username, password
        exit()
    try:
        WebDriverWait(driver, 5).until(lambda webpage: "https://stackoverflow.com/" in webpage.current_url)
        print('\nLogin Successful!\n')
    except TimeoutException:
        print('\nUsername/Password seems to be incorrect, please re-check\nand Re-Run the program.')
        exit()

The above code, takes 2 parameters - gmailID and password. If the password or username is wrong, then you'll notified.

Why stackauth?
-> Stackauth uses OAuth 2.0 authorisation to access Google APIs(here, Google account login needs Google API to work) to securely login a user into his/her Google Account.

Click here to read more about OAuth.

Edit:

I just answered to my own question which I'd posted yesterday thinking that it might help you.
As of now, 2021, it can successfully bypass all the google restrictions that used to occur when logging in.
Feel free to revert back if it doesn't work.
Link to my answer is here

Benjamin Loison
  • 3,782
  • 4
  • 16
  • 33
theycallmepix
  • 474
  • 4
  • 13
1

If your Chrome browser was spun up using Chromedriver, then there is detectable evidence that websites can use to determine if you're using Selenium, and then they can block you. However, if the Chrome browser is spun up before Chromedriver connects to it, then you have a browser that no longer looks like an automation-controlled one. Modern web automation libraries such as undetectable-chromedriver are aware of this, and so they make sure Chrome is spun up before connecting chromedriver to it.

The modern framework that I use for these situations is SeleniumBase in undetected chromedriver mode. Here's a script that you can use to get past automation detection on Google: (Run with python after installing seleniumbase with pip install -U seleniumbase)

from seleniumbase import SB

with SB(uc=True) as sb:
    sb.open("https://www.google.com/gmail/about/")
    sb.click('a[data-action="sign in"]')
    sb.type('input[type="email"]', "NAME@gmail.com")
    sb.click('button:contains("Next")')
    sb.type('input[type="password"]', PASSWORD)
    sb.click('button:contains("Next")')
    sb.sleep(5)
Michael Mintz
  • 9,007
  • 6
  • 31
  • 48
1

I faced the same issue related to the Google Play Login, I resolved the issue using this project "Custom Selenium Chromedriver" Git repo: https://github.com/ultrafunkamsterdam/undetected-chromedriver

Scrape google sides is similar to scrape any other website... the biggest issue here is the security layer in the Login(Obviously Google doesn't want robots in its systems).

Python code snippet:

import undetected_chromedriver as uc

chrome_options = uc.ChromeOptions()

chrome_options.headless = False
chrome_options.add_argument('--no-sandbox')

driver = uc.Chrome(options=chrome_options, use_subprocess=True)
kaliiiiiiiii
  • 925
  • 1
  • 2
  • 21
tanrobles
  • 106
  • 1
  • 2
0

A slow yet good solution would be delaying every key press. Why? because google uses a kind of captcha where it analyzes your typing speed and more things. So if you wanna type a mail or password like example@example.com, you'd have to do this:

for i in "example@example.com\n": #\n because the submit doesn't work in input fields in google sign in, so \n is equivalent of pressing enter
    element.send_keys(i)
    time.sleep(0.4) #don't forget to import time or something else with which you could delay your code!
time.sleep(1) #also this sleep because when the button will redirect url, it'd not reload the site and selenium will not wait so one more sleep

PS: if not working, try changing the values of sleep or any other delaying function

JGFMK
  • 8,425
  • 4
  • 58
  • 92
random_hooman
  • 1,660
  • 7
  • 23