Selenium C# Cheat Sheet

Posted : admin On 1/3/2022

Our guest blogger, Andrew Hinkle, walks us through a checklist of how to setup Selenium with an introduction to DogFoodCon 2019

C# / Selenium Cheat Sheet by deadairx - Cheatography.com Created Date: 3343Z. The Element Click command could not be properly executed as.

Written by Andrew Hinkle • Last Updated: July 31st, 2019 • Develop •

Selenium is a great tool for testing your user interface (UI). There are plenty of great tutorials on the web that I encourage you to review. This article is going to cover some basic setup steps, a simple .NET Core 2.1 code sample, and promote additional resources such as an intermediate session you may attend at Dog Food Con 2019 to learn how to incorporate your Selenium tests into your DevOps pipeline.

Browser Settings

  1. Assumptions: Chrome/Firefox (64-bit)/IE11/Edge (Win10 or higher).
  2. Most of these settings have to be done for IE11 as the modern browsers do this by default or the alternative usually still works.
    1. Always open pop-ups in a new tab.
    2. Turn off pop-up blockers.
    3. IE11: Enable Protected Mode for all security zones.
    4. Disable save password prompts.
    5. When prompted to AutoComplete, click 'No'.
    6. Set zoom to 100%.
  3. Restart the browsers

Windows Settings

  1. Disable the logon screen saver so while you're sitting back watching your automated tests run the screen saver does not kick on ruining your test.
  2. Restart the computer

Set the WebDrivers

  1. IE 11
    1. Under 'The Internet Explorer Driver Server' section > click '32 bit Windows IE'
  2. 64 bit should also work, but some consultants I worked with recommended the 32 bit over 64 bit as of 12/2018
    1. Extract 'IEDriverServer.exe' from the zip to c:Selenium.WebDrivers
  3. Microsoft Edge (EdgeHtml)
    1. Edge version 18 or great, then run the following in command prompt as an administrator
      1. DISM.exe /Online /Add-Capability /CapabilityName:Microsoft.WebDriver~~~~0.0.1.0
      2. Edge version less than 18, then do the following
    2. Under 'Downloads' > Microsoft Edge (EdgeHtml) > click the top Release #####
      1. Save 'MicrosoftWebDriver.exe' to c:Selenium.WebDrivers
  4. Microsoft Edge (Chromium)
    1. Since this version is in Preview I did not download and test but here are the steps
    2. Under 'Downloads' > Microsoft Edge (Chromium) > for the top Release ##### click x64
    3. Extract 'msedgedriver.exe ' from the zip to c:Selenium.WebDrivers
  5. Chrome
    1. Under 'All versions available in Downloads' next to the 'Latest stable release' click the ChromeDriver #.## link > Click 'chromedriver_win32.zip'
    2. Extract 'chromedriver.exe' from the zip to c:Selenium.WebDrivers
  6. Firefox
    1. Under the latest release v#.##.# under 'Assets' click the geckodriver-*-win64.zip
    2. Extract 'geckodriver.exe' from the zip to c:Selenium.WebDrivers
Selenium C# Cheat Sheet

Create the Application

The full source code is in https://github.com/penblade/Tips/tree/master/Tips.Selenium.

  1. Create a new project > MSTest Test Project (.NET Core)
  2. Install the following NuGet packages
    1. WaitHelpers by SeleniumExtras.WaitHelpers (v3.11.0)
      1. Used for StalenessOf checks
    2. Support by Selenium Committers (v3.141.0)
    3. WebDriver by Selenium Committers (v3.141.0)

src/Test/Utilities/BrowserType.cs

WebDriverFactory

Create a factory to get the correct browser web driver.

WebDriverExtensions

I toiled over deciding if I wanted to create class objects vs. extension methods off the IWebDriver. After going back and forth multiple times I settled on the extension methods. After some further research, I decided to follow the naming convention of not including the 'I' in front of the extensions class. I decided to keep the code in the OpenQA.Selenium namespace except for the actual test class, so developers would not have to add another using path.

WebDriverTest

Now that the extensions have been setup, let's add our test. We'll open a web page, click a link, wait until page load, and then scroll to an element.

For the test, I want to loop through the list of browsers as part of the same step to verify I have setup the environment correctly. Once you start looking into adding tests through the pipeline you'll want to look into using a test runner and specify the browser to test at run time via a configuration file.

Resources

Cheat
  1. The full source code is in https://github.com/penblade/Tips/tree/master/Tips.Selenium
  2. Introduction To Selenium Webdriver With C# In Visual Studio 2015
  3. Migrating A Selenium Project From .NET Framework To .NET Core
  4. Most Complete Selenium WebDriver C# Cheat Sheet
  5. DogFoodCon 2018 – Addition by Abstration: A conversation about abstraction and dynamic programming – by Jerren Every
    1. Jerren discussed standard refactoring techniques with Test-Driven Development along with concepts like Page Objects that abstract away logic from data.
  6. Here are some additional Notes on a couple issues I dealt with on setup with potential solutions
    1. My Win10 Chrome kept displaying a Windows Defender message
    2. You're supposed to add your Selenium driver path to the environment variable %PATH%, but I hit the max character limit

DogFoodCon 2019

DogFoodCon is my favorite conference to attend each year which is why I was ecstatic when I was approached to become a volunteer tech blogger. I've written a few articles covering the sessions I've attended so far at DogFoodCon 2017 and DogFoodCon 2018.

Unlike those articles that reviewed a session I've attended, I'll be writing a few articles like this one that will provide some context (when possible) into one of the sessions with the goal to spur some interest and lead those of you with interest into attending the session. Let us know in the comments your thoughts on this type of article. Thanks!

If you followed the source code above or downloaded and ran it yourself, you'll see that the Selenium code brought up the following session.

DogFoodCon > Sessions > Jeff McKenzie – [DevOps] Get Some UI In Your CI

I had a delightful interview with Jeff McKenzie where we discussed the highlights of his session. While there may be a short intro to Selenium, this is an intermediate level session so there is assumed basic knowledge of how to create a Selenium test in Java or C#. We compared and contrasted techniques we've both implemented in our pipelines. Jeff will be providing an overview of the following workflows:

  1. Java > Gherkins/Cucumber > Selenium > Jenkins
    1. 2 years of experience on various projects
  2. C# .NET > SpecFlow > Selenium > Azure DevOps
    1. 5 years of experience on various projects

My team currently works with the workflow: C# .NET > MSTest (Page Object Model) > Selenium > Azure DevOps. I found a lot of common ground and can't wait to compare his process fully with ours.

Jeff McKenzie has been working with Azure DevOps in its various forms since its inception and over the last couple years has translated that knowledge and experience to the Jenkins workflow as well. Testing is one of his passions as evidenced by his dedication to following Test-Driven Development (TDD) (15 years) and Behavior-Driven Development (BDD) (7 years).

By attending this session, you'll learn tried and true patterns to develop the mentioned workflows for testing UI in your DevOps processes.

Special thanks to our Adamantium Sponsor

Insight Digital Innovation

Conclusion

I've provided the basics required to setup Selenium including the environment for Win10 and browsers. The sample code demonstrates how to implement common calls to handle waits, find elements, and wait until page load as extension methods off the IWebDriver to enhance and stream line the process. Next steps would be to learn about the Page Object models. I also plugged a DogFoodCon 2019 session that will teach you how to add your Selenium tests into your DevOps pipeline.

Did I cover Selenium basics? Did I miss any? Did the setup instructions work for you? Do you like the extension methods implementation or do you prefer creating class objects instead?

Did you like the plug for the DogFoodCon session? Would the conference/session get as much attention if it was its own article? Do you like the format of this article? What can I do to improve these articles?

Python selenium commands cheat sheet

Frequently used python selenium commands – Cheat Sheet

To import webdriver module in python use below import statement

Driver setup:
Firefox:
firefoxdriver = webdriver.Firefox(executable_path=”Path to Firefox driver”)

To download: Visit GitHub

Chrome:
chromedriver = webdriver.Chrome(executable_path=”Path to Chrome driver”)

To download: Visit Here

Internet Explorer:
iedriver = webdriver.IE(executable_path=”­Pat­h To­ IEDriverServer.exe”)

To download: Visit Here

Edge:
edgedriver = webdriver.Edge(executable_path=”­Pat­h To­ MicrosoftWebDriver.exe”)

To download: Visit Here

Selenium C# Cheat Sheet Pdf

Opera:
operadriver = webdriver.Opera(executable_path=”­Pat­h To­ operadriver”)

To download: visit GitHub

Safari:

SafariDriver now requires manual installation of the extension prior to automation

Browser Arguments:

–headless

To open browser in headless mode. Works in both Chrome and Firefox browser

–start-maximized

To start browser maximized to screen. Requires only for Chrome browser. Firefox by default starts maximized

–incognito

To open private chrome browser

–disable-notifications

To disable notifications, works Only in Chrome browser

Example:

or

To Auto Download in Chrome:

To Auto Download in Firefox:

We can add any MIME types in the list. MIME for few types of files are given below.

  1. Text File (.txt) – text/plain
  2. PDF File (.pdf) – application/pdf
  3. CSV File (.csv) – text/csv or “application/csv”
  4. MS Excel File (.xlsx) – application/vnd.openxmlformats-officedocument.spreadsheetml.sheet or application/vnd.ms-excel
  5. MS word File (.docx) – application/vnd.openxmlformats-officedocument.wordprocessingml.document
    Zip file (.zip) – application/zip

Note:
The value of browser.download.folderList can be set to either 0, 1, or 2.

0 – Files will be downloaded on the user’s desktop.
1 – Files will be downloaded in the Downloads folder.
2 – Files will be stored on the location specified for the most recent download

Disable notifications in Firefox

firefoxOptions.set_preference(“dom.webnotifications.serviceworker.enabled”, false);
firefoxOptions.set_preference(“dom.webnotifications.enabled”, false);

Open specific Firefox browser using Binary:

Open specific Chrome browser using Binary:
from selenium import webdriver
from selenium.webdriver.chrome.options import Options

options = Options()
options.binary_location = “”
driver = webdriver.Chrome(chrome_options=options, executable_path=””)
driver.get(‘http://google.com/’)

Read Browser Details:

driver.title
driver.window_handles
driver.current_window_handles
driver.current_url
driver.page_source

Go to a specified URL:

driver.get(“http://google.com”)
driver.back()
driver.forward()
driver.refresh()

Locating Elements:

driver.find_element_by_ – To find the first element matching the given locator argument. Returns a WebElement

driver.find_elements_by_ – To find all elements matching the given locator argument. Returns a list of WebElement

By ID

<input id=”q” type=”text” />

element = driver.find_element_by_id(“q”)

By Name

<input id=”q” name=”search” type=”text” />

element = driver.find_element_by_name(“search”)

By Class Name

<div class=”username” style=”display: block;”>…</div>

element = driver.find_element_by_class_name(“username”)

By Tag Name

<div class=”username” style=”display: block;”>…</div>

element = driver.find_element_by_tag_name(“div”)

By Link Text

<a href=”#”>Refresh</a>

element = driver.find_element_by_link_text(“Refresh”)

By Partial Link Text

<a href=”#”>Refresh Here</a>

element = driver.find_element_by_partial_link_text(“Refresh”)

By XPath

<form id=”testform” action=”submit” method=”get”>

Username: <input type=”text” />
Password: <input type=”password” />

</form>

element = driver.find_element_by_xpath(“//form[@id=’testform’]/input[1]”)

By CSS Selector

<form id=”testform” action=”submit” method=”get”>

<input class=”username” type=”text” />
<input class=”password” type=”password” />

</form>

element = driver.find_element_by_css_selector(“form#testform>input.username”)

Important Modules to Import:

from selenium import webdriver
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.support.ui import Select

from selenium.webdriver.common.by import By
from selenium.webdriver.common.action_chains import ActionChains

from selenium.common.exceptions import NoSuchElementException

from selenium.webdriver.firefox.firefox_binary import FirefoxBinary

from selenium.webdriver.chrome.options import Options
from selenium.webdriver.firefox.options import Options

Python Selenium commands for operation on elements:

button/link/image:

click()
get_attribute()
is_displayed()
is_enabled()

Text field:

Selenium C# Cheat Sheet 2020

send_keys()
clear()

Checkbox/Radio:

is_selected()
click()

Select:

Find out the select element using any element locating strategies and then select options from list using index, visible text or option value.

Element properties:

Selenium C# Cheat Sheet For Beginners

is_displayed()
is_selected()
is_enabled()

These methods return either true or false.

Read Attribute:

get_attribute(“”)

Get attribute from a disabled text box

driver.find_element_by_id(“id”).get_attribute(“value”);

Screenshot:

Selenium C# Cheat Sheet Pdf

Note: An important note to store screenshots is that save_screenshot(‘filename’) and get_screenshot_as_file(‘filename’) will work only when extension of file is ‘.png’. Otherwise content of the screenshot can’t be viewed

Selenium C# Cheat Sheet 2019

Read articles for more details about taking screenshot and element screenshot

The list here contains mostly used python selenium commands but not exhaustive. Please feel free to add in comments if you feel something is missing and should be here.

Selenium C# Cheatsheet

3 Responses

Selenium C# Code Examples

  1. […] Previous: Previous post: Execute Python Selenium tests in Selenium GridNext: Next post: Python selenium commands cheat sheet […]

  2. Thank you very much

  3. Hi Sir,

    I am trying to do the sorting in selenium with python using For loop could u please help me is there any way that i can do it ?

    Sorting in descending order in the below website

    website: https://jqueryui.com/sortable/