How to log in to Chrome with Selenium?

16,719

Solution 1

You may need to login manually once and then use that for automation. Try below code , may be it help you:

System.setProperty("webdriver.chrome.driver","<chrome exe path>");
ChromeOptions options = new ChromeOptions();
options.addArguments("user-data-dir= <full local path Google Chrome user data default folder>);

WebDriver driver = new ChromeDriver(options);
driver.get("https://mail.google.com");

Login once manually when browser launched.

Then re-run script now it should use previous login.

Hope it will help you.

Solution 2

I think you can still login automatically. The reason is, when opening the page chrome://chrome-signin, the account textbox is automatically focused, so you just need to use keyboards to login without knowing how the html of the page looks like.

Try the code below (you might need to put some sleep in some places to make sure that everything is loaded properly.

public void loginToChrome(username, password) {
    driver.get("chrome://chrome-signin");
    var action = new Actions(driver);
    action.sendKeys(username).perform();
    action.sendKeys(keys.ENTER).perform();
    action.sendKeys(password).perform();
    action.sendKeys(keys.ENTER).perform();
}
Share:
16,719
ThisIsNoZaku
Author by

ThisIsNoZaku

I downvote code-only answers.

Updated on June 04, 2022

Comments

  • ThisIsNoZaku
    ThisIsNoZaku almost 2 years

    I am testing a Chrome extension which requires the user to be logged in to use, but I cannot figure out how to login with my test account. I have tried logging in to accounts.google.com but this is apparently insufficient; as far as the chrome APIs are concerned there is no authenticated user.

    Chrome keeps prompting for login at chrome://chrome-signin but because I can't view the html of the page I can't determine what elements to interact with in Selenium to use it.

  • ThisIsNoZaku
    ThisIsNoZaku almost 7 years
    It's a shame that it apparently can't be fully automated but the problem does appear fixed.
  • Philipp Nies
    Philipp Nies about 5 years
    I get the message that the synchronization has been disabled by the administrator. Is there a way to confirm this "alert"? Since it is not a typical old one, it can not be confirmed with driver.switchTo().alert().accept()