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

Most Complete Selenium Webdriver C# Cheat Sheet: @"pathtoimage"

This document provides a summary of advanced Selenium WebDriver operations for browsers like Chrome, Firefox, IE, and Edge. It discusses how to handle pop-ups and tabs, navigate browser history, maximize the window, add and delete cookies, take screenshots, switch frames, and configure the browser using options like proxies and certificates. Advanced element operations like drag and drop are also covered.

Uploaded by

naren_reddys
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
289 views

Most Complete Selenium Webdriver C# Cheat Sheet: @"pathtoimage"

This document provides a summary of advanced Selenium WebDriver operations for browsers like Chrome, Firefox, IE, and Edge. It discusses how to handle pop-ups and tabs, navigate browser history, maximize the window, add and delete cookies, take screenshots, switch frames, and configure the browser using options like proxies and certificates. Advanced element operations like drag and drop are also covered.

Uploaded by

naren_reddys
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 1

Advanced Browser Operations

Most Complete Selenium


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

Basic Browser Operations Advanced Browser Configurations


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

You might also like