Algorithms in C#  

Advanced Selenium Chrome Automation in C#

Selenium WebDriver is a versatile tool for browser automation. While the basic examples work, real-world web applications require handling dynamic elements, forms, alerts, waits, and robust error handling. Here’s a step-by-step guide for advanced automation with Chrome in C#.

1. Setup

Ensure you have:

  • Visual Studio installed: Visual Studio

  • Selenium WebDriver and ChromeDriver installed via NuGet:

Install-Package Selenium.WebDriver
Install-Package Selenium.WebDriver.ChromeDriver
Install-Package Selenium.Support

2. ChromeDriver with Options

Using ChromeOptions allows you to run Chrome in maximized mode, headless mode, or with custom preferences:

ChromeOptions options = new ChromeOptions();
options.AddArgument("--start-maximized"); // maximize window
options.AddArgument("--disable-infobars"); // disable infobars
options.AddArgument("--headless"); // optional: run headless

3. Explicit Waits (Best Practice)

Avoid Thread.Sleep(); instead, use WebDriverWait for dynamic elements:

using OpenQA.Selenium.Support.UI;

// Wait for element to be visible
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
IWebElement searchBox = wait.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementIsVisible(By.Name("q")));

4. Handling Forms and Dynamic Elements

Example: Automating Google search and clicking the first result.

using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Support.UI;
using System;

namespace AdvancedSeleniumExample
{
    class Program
    {
        static void Main(string[] args)
        {
            ChromeOptions options = new ChromeOptions();
            options.AddArgument("--start-maximized");

            using (IWebDriver driver = new ChromeDriver(options))
            {
                try
                {
                    driver.Navigate().GoToUrl("https://www.google.com");

                    WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
                    
                    // Accept Cookies if present
                    try
                    {
                        IWebElement acceptCookies = wait.Until(
                            SeleniumExtras.WaitHelpers.ExpectedConditions.ElementToBeClickable(By.Id("L2AGLb")));
                        acceptCookies.Click();
                    }
                    catch { /* No cookies popup */ }

                    // Search query
                    IWebElement searchBox = wait.Until(
                        SeleniumExtras.WaitHelpers.ExpectedConditions.ElementIsVisible(By.Name("q")));
                    searchBox.SendKeys("Selenium C# advanced tutorial");
                    searchBox.SendKeys(Keys.Enter);

                    // Wait for results to load
                    IWebElement firstResult = wait.Until(
                        SeleniumExtras.WaitHelpers.ExpectedConditions.ElementIsVisible(By.CssSelector("h3")));
                    Console.WriteLine("First Result: " + firstResult.Text);

                    // Click the first result
                    firstResult.Click();

                    // Wait for page to load and take a screenshot
                    System.Threading.Thread.Sleep(2000); // optional short wait
                    Screenshot screenshot = ((ITakesScreenshot)driver).GetScreenshot();
                    screenshot.SaveAsFile("GoogleResult.png", ScreenshotImageFormat.Png);
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Error: " + ex.Message);
                }
                finally
                {
                    driver.Quit();
                }
            }
        }
    }
}

5. Handling Alerts, Pop-ups, and Frames

  • Alerts

IAlert alert = driver.SwitchTo().Alert();
alert.Accept(); // or alert.Dismiss();
  • Frames

driver.SwitchTo().Frame("frameNameOrId");
// perform actions
driver.SwitchTo().DefaultContent();
  • Windows/Tabs

var originalWindow = driver.CurrentWindowHandle;
driver.SwitchTo().Window(driver.WindowHandles[1]); // switch to new tab

6. Headless Mode Automation

For CI/CD pipelines or server automation, headless mode is essential:

ChromeOptions options = new ChromeOptions();
options.AddArgument("--headless");
options.AddArgument("--window-size=1920,1080");

7. Taking Screenshots

Always useful for debugging or logging test failures:

Screenshot screenshot = ((ITakesScreenshot)driver).GetScreenshot();
screenshot.SaveAsFile("screenshot.png", ScreenshotImageFormat.Png);

8. Best Practices

  1. Use Explicit Waits over Thread.Sleep().

  2. Handle exceptions gracefully to prevent browser hanging.

  3. Use Page Object Model (POM) for maintainable test scripts.

  4. Keep ChromeDriver updated with your Chrome version: ChromeDriver

  5. Use Headless Mode for automated servers.

✅ With this setup, you can automate complex web workflows, dynamic content, popups, and multi-tab interactions in Chrome using C#. This is production-ready and integrates well with automated testing frameworks.