How to log-in on Google using Selenium Headless in C#

0

I want to log-in to Google using the Selenium WebDriver and the process works normally when the WebDriver is in normal state where it opens a Chrome browser window however if used with the "--headless" and "--disable-gpu" parameters the code throws an NoSuchElementException error.

My code:

        var chromeDriverService = ChromeDriverService.CreateDefaultService();
        chromeDriverService.HideCommandPromptWindow = false;

        ChromeOptions chrOptions = new ChromeOptions();
        chrOptions.AddArgument("--headless");
        chrOptions.AddArgument("start-maximized");
        chrOptions.AddArgument("disable-infobars");
        chrOptions.AddArgument("--disable-extensions");
        //chrOptions.AddArguments("window-size=1920,1080");

        IWebDriver driver = new ChromeDriver(chromeDriverService, chrOptions);

        driver.Url = "https://www.google.com";

        var button1 = driver.FindElement(By.XPath("//*[@id=\"gb_70\"]"));
        button1.Click();

        var login = driver.FindElement(By.Id("identifierId"));
        login.SendKeys(Username);
        var next0 = driver.FindElement(By.XPath("//*[@id=\"identifierNext\"]/content/span"));
        next0.Click();

        var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(5));
        wait.Until(ExpectedConditions.ElementIsVisible(By.XPath("//*[@id=\"password\"]/div[1]/div/div[1]/input")));
        Thread.Sleep(3000);

        var passw = driver.FindElement(By.XPath("//*[@id=\"password\"]/div[1]/div/div[1]/input"));
        passw.SendKeys(Password);

        var final = driver.FindElement(By.XPath("//*[@id=\"passwordNext\"]/content/span"));
        final.Click();

Actual output:

OpenQA.Selenium.NoSuchElementException HResult=0x80131500 Message=no such element: Unable to locate element: {"method":"id","selector":"identifierId"} (Session info: headless chrome=74.0.3729.131) (Driver info: chromedriver=74.0.3729.6 (255758eccf3d244491b8a1317aa76e1ce10d57e9-refs/branch-heads/3729@{#29}),platform=Windows NT 10.0.17134 x86_64) Source=WebDriver

Expected output: Successful log-in to Google.

I would also like to add that I have tried countless different methods and none are working and having been trying to find other solutions. Ultimately it brings me down to one error I saw in the console once which stated something along the lines of: "could not display URLHERE because it's x-frame-options is set to deny" After further research I've found it is some sort of security to prevent click-hijacking.

Is there another way to do this using WebRequests or HttpWebRequests? Maybe I could log-in using WebRequests and transfer the cookies over to Selenium driver. Would that work?

c#
selenium
asked on Stack Overflow May 10, 2019 by mattxd00

0 Answers

Nobody has answered this question yet.


User contributions licensed under CC BY-SA 3.0