Find HTML Element by Class Name in Selenium

using System;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;

namespace MySeleniumApp
{
    class Program
    {
        static void Main(string[] args)
        {
            // Initialize the Chrome Driver
            using (IWebDriver driver = new ChromeDriver())
            {
                // Navigate to a website
                driver.Navigate().GoToUrl("https://www.example.com");

                // Find element by its class name
                IWebElement element = driver.FindElement(By.ClassName("element_class_name_here"));

                // Perform actions on the element (e.g., click, send keys, etc.)
                string elementText = element.Text;

                // Output the text of the element
                Console.WriteLine($"Element text is: {elementText}");

                // Close the driver
                driver.Quit();
            }
        }
    }
}

 

Find HTML Element by Id in Selenium

using System;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;

namespace MySeleniumApp
{
    class Program
    {
        static void Main(string[] args)
        {
            // Initialize the Chrome Driver
            using (IWebDriver driver = new ChromeDriver())
            {
                // Navigate to a website
                driver.Navigate().GoToUrl("https://www.example.com");

                // Find element by its id
                IWebElement element = driver.FindElement(By.Id("element_id_here"));

                // Perform actions on the element (e.g., click, send keys, etc.)
                string elementText = element.Text;

                // Output the text of the element
                Console.WriteLine($"Element text is: {elementText}");

                // Close the driver
                driver.Quit();
            }
        }
    }
}

 

Running Selenium in a virtual desktop environment on Linux

Running Selenium tests in a virtual desktop environment on Linux can be particularly useful for isolating the browser and running tests as if they were in a GUI, without interfering with the actual display. A common tool for creating a virtual desktop on Linux is Xvfb (X Virtual FrameBuffer).

First, you need to install Xvfb. You can install it using your distribution’s package manager. For Ubuntu/Debian:

sudo apt-get update
sudo apt-get install -y xvfb

Start Xvfb on a particular display

Xvfb :99 -ac &

Export DISPLAY Environment Variable

You need to tell your terminal session to send any graphical output to the virtual frame buffer set up by Xvfb. You can do this by setting the DISPLAY environment variable.

export DISPLAY=:99

Run Your Selenium Test

Now you can run your Selenium test as you would normally, and it will send its output to the virtual frame buffer instead of trying to use a physical display.

Here is a sample C# code snippet that opens Google in Chrome. Make sure you have the Selenium WebDriver NuGet package and ChromeDriver installed.

using System;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;

namespace MySeleniumApp
{
    class Program
    {
        static void Main(string[] args)
        {
            // Initialize ChromeDriver
            using (IWebDriver driver = new ChromeDriver())
            {
                // Navigate to Google
                driver.Navigate().GoToUrl("https://www.google.com");
                
                // Do your test logic here
                
                // Close the driver
                driver.Quit();
            }
        }
    }
}

Stop Xvfb

After you’ve finished running your tests, you can stop the Xvfb process.

killall Xvfb

Configure Xvfb directly within your C# code

To configure a virtual desktop like Xvfb directly within your C# code, you can use the System.Diagnostics.Process class to start and stop the Xvfb process. This approach can be useful for programmatically managing the virtual display environment.

Here’s an example that demonstrates how to start Xvfb, set the DISPLAY environment variable, and then run a Selenium test—all within the C# code.

using System;
using System.Diagnostics;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;

namespace MySeleniumApp
{
    class Program
    {
        static void Main(string[] args)
        {
            // Start Xvfb on display 99
            Process xvfbProcess = new Process();
            xvfbProcess.StartInfo.FileName = "Xvfb";
            xvfbProcess.StartInfo.Arguments = ":99 -ac";
            xvfbProcess.StartInfo.RedirectStandardOutput = true;
            xvfbProcess.StartInfo.UseShellExecute = false;
            xvfbProcess.StartInfo.CreateNoWindow = true;
            xvfbProcess.Start();

            // Wait for Xvfb to initialize
            System.Threading.Thread.Sleep(2000);

            // Set the DISPLAY environment variable
            Environment.SetEnvironmentVariable("DISPLAY", ":99");

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

                // Do your test logic here

                // Close the driver
                driver.Quit();
            }

            // Stop Xvfb process
            xvfbProcess.Kill();
        }
    }
}

By using this approach, you can encapsulate the entire process of setting up a virtual display and running a Selenium test in your C# code, making it easier to integrate into your automated testing workflow.

Running Selenium without a GUI

Running Selenium without a GUI is known as running it in “headless” mode. In this mode, the browser doesn’t display a user interface, which is particularly useful for automated tests that run on servers or other environments where a graphical display is not available.

using System;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;

namespace MySeleniumApp
{
    class Program
    {
        static void Main(string[] args)
        {
            // Initialize ChromeDriver options
            ChromeOptions options = new ChromeOptions();
            options.AddArgument("--headless");  // Run headless
            
            // Initialize the Chrome Driver with options
            using (IWebDriver driver = new ChromeDriver(options))
            {
                // Navigate to Google
                driver.Navigate().GoToUrl("https://www.google.com");

                // Optionally, capture the page title to verify
                Console.WriteLine("Page title is: " + driver.Title);

                // Close the driver
                driver.Quit();
            }
        }
    }
}

Chrome will run in headless mode, performing all the actions but without displaying the browser GUI. You should see the page title printed in the console if everything works correctly.

The ability to run tests in headless mode can be particularly useful in an automated testing environment or a CI/CD pipeline.

Install Selenium WebDriver for .NET Core

Run the following command to install the Selenium WebDriver NuGet package:

dotnet add package Selenium.WebDriver

You’ll also need to download the WebDriver executable for the browser you intend to use. For example, if you are planning to use Chrome, you’ll need to download ChromeDriver.

You can download it from the official site and place the executable in a directory that is in your system’s PATH, or specify its location in your code.

Write Your Test Code

Now you can write your Selenium test code in the Program.cs file. Here’s a simple example to open Google’s homepage:

using System;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;

namespace MySeleniumApp
{
    class Program
    {
        static void Main(string[] args)
        {
            // Initialize the Chrome Driver
            using (IWebDriver driver = new ChromeDriver())
            {
                // Navigate to Google
                driver.Navigate().GoToUrl("https://www.google.com");

                // Close the driver
                driver.Close();
            }
        }
    }
}

 

Disable wermgr.exe on Windows

Using Services

  1. Press Win + R to open the Run dialog.
  2. Type services.msc and press Enter.
  3. Scroll down and locate the Windows Error Reporting Service.
  4. Right-click on it and choose Properties.
  5. In the Startup type dropdown, select Disabled.
  6. Click Apply and then OK.

Using Registry Editor

  1. Press Win + R to open the Run dialog.
  2. Type regedit and press Enter.
  3. Navigate to HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\Windows Error Reporting.
  4. Create a new DWORD value named Disabled and set its value to 1.

 

Ignoring SSL certificate errors in C# RestSharp Library

//bypass ssl validation check by using RestClient object
var options = new RestClientOptions(baseurl) {
    RemoteCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true;
};
var restClient = new RestClient(options);

or in application level

//bypass ssl validation check globally for whole application.
ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) => true;

 

Ignoring SSL certificate errors in C# HttpClient

var handler = new HttpClientHandler();
handler.ClientCertificateOptions = ClientCertificateOption.Manual;
handler.ServerCertificateCustomValidationCallback = 
    (httpRequestMessage, cert, cetChain, policyErrors) =>
{
    return true;
};

var client = new HttpClient(handler);

 

Preferred Challenges for Certbot

The preferred challenges for Certbot are usually one of the following:

  1. HTTP-01 Challenge: This is the most common challenge type. Certbot will create a temporary file on your web server, and the Let’s Encrypt servers will try to access that file over HTTP. You’ll need to make sure that port 80 is open and that your web server is configured to serve files from the hidden .well-known directory.
  2. DNS-01 Challenge: This challenge requires you to add a specific DNS TXT record to your domain’s DNS settings. This is often used when you need to obtain a wildcard certificate or when the HTTP challenge is not suitable. It might require manual intervention if you don’t have a DNS provider with an API that Certbot can use.
  3. TLS-ALPN-01 Challenge: This challenge requires setting up a special TLS certificate on your server and is less commonly used. It’s generally more complex to set up compared to the HTTP-01 challenge.

The HTTP-01 challenge is often the easiest to use, especially for standard web server setups, while the DNS-01 challenge is necessary for more complex scenarios like wildcard certificates.

You can specify the challenge type when running Certbot with the --preferred-challenges option, followed by the challenge type, such as:

certbot --preferred-challenges http

or

certbot --preferred-challenges dns

Keep in mind that depending on your specific setup and requirements, you might need to choose a specific challenge type or follow additional steps to successfully obtain a certificate.