0% found this document useful (0 votes)
628 views

Most Complete Selenium Webdriver C# Cheat Sheet: Initialize Advanced Browser Operations

This document provides a summary of Selenium WebDriver C# methods for initializing browsers, locating elements, basic and advanced browser and element operations, and advanced browser configurations. It includes code examples for initializing Chrome, Firefox, IE, and Edge browsers; finding elements by class, CSS, ID, link text, name, partial link text, tag name, and XPath; clicking elements, sending keys, clearing fields, submitting forms, getting text and attributes; selecting options from drop-down menus; dragging and dropping elements; checking element visibility; uploading files; handling alerts and windows; taking screenshots; waiting for page loads; switching frames; setting HTTP proxies; and accepting untrusted certificates.

Uploaded by

Lasha Kvara
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
628 views

Most Complete Selenium Webdriver C# Cheat Sheet: Initialize Advanced Browser Operations

This document provides a summary of Selenium WebDriver C# methods for initializing browsers, locating elements, basic and advanced browser and element operations, and advanced browser configurations. It includes code examples for initializing Chrome, Firefox, IE, and Edge browsers; finding elements by class, CSS, ID, link text, name, partial link text, tag name, and XPath; clicking elements, sending keys, clearing fields, submitting forms, getting text and attributes; selecting options from drop-down menus; dragging and dropping elements; checking element visibility; uploading files; handling alerts and windows; taking screenshots; waiting for page loads; switching frames; setting HTTP proxies; and accepting untrusted certificates.

Uploaded by

Lasha Kvara
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 1

Most Complete Selenium

WebDriver C# Cheat Sheet

Initialize Advanced Browser Operations


// NuGet: Selenium.WebDriver.ChromeDriver // Handle JavaScript pop-ups
using OpenQA.Selenium.Chrome; IAlert a = driver.SwitchTo().Alert();
IWebDriver driver = new ChromeDriver(); a.Accept();
// NuGet: Selenium.Mozilla.Firefox.Webdriver a.Dismiss();
using OpenQA.Selenium.Firefox; // Switch between browser windows or tabs
IWebDriver driver = new FirefoxDriver(); ReadOnlyCollection<string> windowHandles = driver.WindowHandles;
// NuGet: Selenium.WebDriver.IEDriver string firstTab = windowHandles.First();
using OpenQA.Selenium.IE; string lastTab = windowHandles.Last();
IWebDriver driver = new InternetExplorerDriver(); driver.SwitchTo().Window(lastTab);
// NuGet: Selenium.WebDriver.EdgeDriver // Navigation history
using OpenQA.Selenium.Edge; this.driver.Navigate().Back();
IWebDriver driver = new EdgeDriver(); this.driver.Navigate().Refresh();
this.driver.Navigate().Forward();
// Option 1.
link.SendKeys(string.Empty);
Locators // Option 2.
((IJavaScriptExecutor)driver).ExecuteScript("arguments[0].focus();",
this.driver.FindElement(By.ClassName("className")); link);
this.driver.FindElement(By.CssSelector("css")); // Maximize window
this.driver.FindElement(By.Id("id")); this.driver.Manage().Window.Maximize();
this.driver.FindElement(By.LinkText("text")); // Add a new cookie
this.driver.FindElement(By.Name("name")); Cookie cookie = new OpenQA.Selenium.Cookie("key", "value");
this.driver.FindElement(By.PartialLinkText("pText")); this.driver.Manage().Cookies.AddCookie(cookie);
this.driver.FindElement(By.TagName("input")); // Get all cookies
this.driver.FindElement(By.XPath("//*[@id='editor']")); var cookies = this.driver.Manage().Cookies.AllCookies;
// Find multiple elements // Delete a cookie by name
IReadOnlyCollection<IWebElement> anchors = this.driver.Manage().Cookies.DeleteCookieNamed("CookieName");
this.driver.FindElements(By.TagName("a")); // Delete all cookies
// Search for an element inside another this.driver.Manage().Cookies.DeleteAllCookies();
var div = this.driver.FindElement(By.TagName("div")) // Taking a full-screen screenshot
.FindElement(By.TagName("a")); Screenshot screenshot = ((ITakesScreenshot)driver).GetScreenshot();
screenshot.SaveAsFile(@"pathToImage", ImageFormat.Png);
// Wait until a page is fully loaded via JavaScript
WebDriverWait wait = new WebDriverWait(this.driver,
Basic Browser Operations TimeSpan.FromSeconds(30));
wait.Until((x) =>
{
// Navigate to a page
return ((IJavaScriptExecutor)this.driver).ExecuteScript(
this.driver.Navigate().GoToUrl(@"http://google.com");
"return document.readyState").Equals("complete");
// Get the title of the page
});
string title = this.driver.Title;
// Switch to frames
// Get the current URL
this.driver.SwitchTo().Frame(1);
string url = this.driver.Url;
this.driver.SwitchTo().Frame("frameName");
// Get the current page HTML source
IWebElement element = this.driver.FindElement(By.Id("id"));
string html = this.driver.PageSource;
this.driver.SwitchTo().Frame(element);

// Switch to the default document


Basic Elements Operations this.driver.SwitchTo().DefaultContent();

IWebElement element = driver.FindElement(By.Id("id"));


element.Click(); Advanced Browser Confgurations
element.SendKeys("someText");
element.Clear();
// Use a specific Firefox profile
element.Submit();
FirefoxProfileManager profileManager = new FirefoxProfileManager();
string innerText = element.Text;
FirefoxProfile profile = profileManager.GetProfile("HARDDISKUSER");
bool isEnabled = element.Enabled;
IWebDriver driver = new FirefoxDriver(profile);
bool isDisplayed = element.Displayed;
// Set a HTTP proxy Firefox
bool isSelected = element.Selected;
FirefoxProfile firefoxProfile = new FirefoxProfile();
IWebElement element = driver.FindElement(By.Id("id"));
firefoxProfile.SetPreference("network.proxy.type", 1);
SelectElement select = new SelectElement(element);
firefoxProfile.SetPreference("network.proxy.http", "myproxy.com");
select.SelectByIndex(1);
firefoxProfile.SetPreference("network.proxy.http_port", 3239);
select.SelectByText("Ford");
IWebDriver driver = new FirefoxDriver(firefoxProfile);
select.SelectByValue("ford");
// Set a HTTP proxy Chrome
select.DeselectAll();
ChromeOptions options = new ChromeOptions();
select.DeselectByIndex(1);
var proxy = new Proxy();
select.DeselectByText("Ford");
proxy.Kind = ProxyKind.Manual;
select.DeselectByValue("ford");
proxy.IsAutoDetect = false;
IWebElement selectedOption = select.SelectedOption;
proxy.HttpProxy = "127.0.0.1:3239";
IList<IWebElement> allSelected = select.AllSelectedOptions;
proxy.SslProxy = "127.0.0.1:3239";
bool isMultipleSelect = select.IsMultiple;
options.Proxy = proxy;
options.AddArgument("ignore-certificate-errors");
IWebDriver driver = new ChromeDriver(options);
Advanced Element Operations // Accept all certificates Firefox
FirefoxProfile firefoxProfile = new FirefoxProfile();
firefoxProfile.AcceptUntrustedCertificates = true;
// Drag and Drop firefoxProfile.AssumeUntrustedCertificateIssuer = false;
IWebElement element = driver.FindElement( IWebDriver driver = new FirefoxDriver(firefoxProfile);
By.XPath("//*[@id='project']/p[1]/div/div[2]")); // Accept all certificates Chrome
Actions move = new Actions(driver); DesiredCapabilities capability = DesiredCapabilities.Chrome();
move.DragAndDropToOffset(element, 30, 0).Perform(); Environment.SetEnvironmentVariable("webdriver.chrome.driver",
// How to check if an element is visible "C:\\PathToChromeDriver.exe");
Assert.IsTrue(driver.FindElement( capability.SetCapability(CapabilityType.AcceptSslCertificates, true);
By.XPath("//*[@id='tve_editor']/div")).Displayed); IWebDriver driver = new RemoteWebDriver(capability);
// Upload a file // Set Chrome options.
IWebElement element = ChromeOptions options = new ChromeOptions();
driver.FindElement(By.Id("RadUpload1file0")); DesiredCapabilities dc = DesiredCapabilities.Chrome();
String filePath = @"D:\WebDriver.Series.Tests\\WebDriver.xml"; dc.SetCapability(ChromeOptions.Capability, options);
element.SendKeys(filePath); IWebDriver driver = new RemoteWebDriver(dc);
// Scroll focus to control // Turn off the JavaScript Firefox
IWebElement link = FirefoxProfileManager profileManager = new FirefoxProfileManager();
driver.FindElement(By.PartialLinkText("Previous post")); FirefoxProfile profile = profileManager.GetProfile("HARDDISKUSER");
string js = string.Format("window.scroll(0, {0});", profile.SetPreference("javascript.enabled", false);
link.Location.Y); IWebDriver driver = new FirefoxDriver(profile);
((IJavaScriptExecutor)driver).ExecuteScript(js); // Set the default page load timeout
link.Click(); driver.Manage().Timeouts().SetPageLoadTimeout(new TimeSpan(10));
// Taking an element screenshot // Start Firefox with plugins
IWebElement element = FirefoxProfile profile = new FirefoxProfile();
driver.FindElement(By.XPath("//*[@id='tve_editor']/div")); profile.AddExtension(@"C:\extensionsLocation\extension.xpi");
var cropArea = new Rectangle(element.Location, element.Size); IWebDriver driver = new FirefoxDriver(profile);
var bitmap = bmpScreen.Clone(cropArea, bmpScreen.PixelFormat); // Start Chrome with an unpacked extension
bitmap.Save(fileName); ChromeOptions options = new ChromeOptions();
// Focus on a control options.AddArguments("load-extension=/pathTo/extension");
IWebElement link = DesiredCapabilities capabilities = new DesiredCapabilities();
driver.FindElement(By.PartialLinkText("Previous post")); capabilities.SetCapability(ChromeOptions.Capability, options);
// Wait for visibility of an element DesiredCapabilities dc = DesiredCapabilities.Chrome();
WebDriverWait wait = new WebDriverWait(driver, dc.SetCapability(ChromeOptions.Capability, options);
TimeSpan.FromSeconds(30)); IWebDriver driver = new RemoteWebDriver(dc);
wait.Until(ExpectedConditions.VisibilityOfAllElementsLocatedBy( // Start Chrome with a packed extension
By.XPath("//*[@id='tve_editor']/div[2]/div[2]/div/div"))); ChromeOptions options = new ChromeOptions();
options.AddExtension(Path.GetFullPath("localpathto/extension.crx"));
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.SetCapability(ChromeOptions.Capability, options);
DesiredCapabilities dc = DesiredCapabilities.Chrome();
dc.SetCapability(ChromeOptions.Capability, options);
IWebDriver driver = new RemoteWebDriver(dc);
// Change the default files’ save location
String downloadFolderPath = @"c:\temp";
FirefoxProfile profile = new FirefoxProfile();
profile.SetPreference("browser.download.folderList", 2);
profile.SetPreference("browser.download.dir", downloadFolderPath);
profile.SetPreference("browser.download.manager.alertOnEXEOpen",
false);
profile.SetPreference("browser.helperApps.neverAsk.saveToDisk",
"application/msword, application/binary, application/ris, text/csv,
image/png, application/pdf, text/html, text/plain, application/zip,
application/x-zip, application/x-zip-compressed,
application/download, application/octet-stream");
this.driver = new FirefoxDriver(profile);

You might also like