59

Most Complete Selenium WebDriver VB.NET Cheat Sheet

 3 years ago
source link: https://www.automatetheplanet.com/selenium-webdriver-vbn-cheat-sheet/?utm_campaign=selenium-webdriver-vbn-cheat-sheet
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Most Complete Selenium WebDriver VB.NET Cheat Sheet

Most Complete Selenium WebDriver VB.NET Cheat Sheet

As you know, I am a big fan of Selenium WebDriver. You can find tones of useful code in my WebDriver Series. I lead automated testing courses and train people how to write tests all the time. The thing that I felt that is missing in the materials was a sheet containing all of the most relevant code snippets. If you google it, you will find several similar cheat sheets (Java, Python), but the VB.NET one was missing. So I decided to fill that gap. So, I created the first and most complete Selenium WebDriver VB.NET cheat sheet. I hope that you will find it useful. Enjoy!

Initialize

' NuGet: Selenium.WebDriver.ChromeDriverImports OpenQA.Selenium.ChromePrivate driverField As IWebDriver = New ChromeDriver()' NuGet: Selenium.Mozilla.Firefox.Webdriverfile:///D:/pdfmaker/assets/mvup.pngPrivate driverField1 As IWebDriver = New FirefoxDriver()Imports OpenQA.Selenium.Firefox' NuGet: Selenium.WebDriver.IEDriverImports OpenQA.Selenium.IEPrivate driverField2 As IWebDriver = New InternetExplorerDriver()' NuGet: Selenium.WebDriver.EdgeDriverImports OpenQA.Selenium.Edge Private driver As IWebDriver = New EdgeDriver()

Locators

_driver.FindElement(By.ClassName("className"))_driver.FindElement(By.CssSelector("css"))file:///D:/pdfmaker/assets/nwcl.png_driver.FindElement(By.Id("id"))_driver.FindElement(By.LinkText("text"))_driver.FindElement(By.Name("name"))_driver.FindElement(By.PartialLinkText("pText"))_driver.FindElement(By.TagName("input"))_driver.FindElement(By.XPath("//*[@id='editor']"))' Find multiple elementsDim anchors As IReadOnlyCollection(Of IWebElement) = _driver.FindElements(By.TagName("a"))' Search for an element inside anotherDim div = _driver.FindElement(By.TagName("div")).FindElement(By.TagName("a"))

Basic Elements Operations

Dim element = _driver.FindElement(By.Id("id"))element.Click()element.SendKeys("someText")element.Clear()element.Submit()Dim innerText = element.TextDim isEnabled = element.EnabledDim isDisplayed = element.DisplayedDim isSelected = element.SelectedDim element = _driver.FindElement(By.Id("id"))Dim [select] As SelectElement = New SelectElement(element)[select].SelectByIndex(1)[select].SelectByText("Ford")[select].SelectByValue("ford")[select].DeselectAll()[select].DeselectByIndex(1)[select].DeselectByText("Ford")[select].DeselectByValue("ford")Dim selectedOption = [select].SelectedOptionDim allSelected = [select].AllSelectedOptionsDim isMultipleSelect = [select].IsMultiple

Advanced Elements Operations

' Drag and DropDim element = _driver.FindElement(By.XPath("//*[@id='project']/p[1]/div/div[2]"))Dim move As Actions = New Actions(_driver)move.DragAndDropToOffset(element, 30, 0).Perform()' How to check if an element is visibleAssert.IsTrue(_driver.FindElement(By.XPath("//*[@id='tve_editor']/div")).Displayed)' Upload a fileDim element = _driver.FindElement(By.Id("RadUpload1file0"))Dim filePath = "D:WebDriver.Series.TestsWebDriver.xml"element.SendKeys(filePath)' Scroll focus to controlDim link = _driver.FindElement(By.PartialLinkText("Previous post"))Dim js = String.Format("window.scroll(0, {0});", link.Location.Y)CType(_driver, IJavaScriptExecutor).ExecuteScript(js)link.Click()' Taking an element screenshotDim element = _driver.FindElement(By.XPath("//*[@id='tve_editor']/div"))Dim cropArea = New Rectangle(element.Location, element.Size)Dim bitmap = bmpScreen.Clone(cropArea, bmpScreen.PixelFormat)bitmap.Save(fileName)' Focus on a controlDim link = _driver.FindElement(By.PartialLinkText("Previous post"))' Wait for visibility of an elementDim wait As WebDriverWait = New WebDriverWait(_driver, TimeSpan.FromSeconds(30))wait.Until(ExpectedConditions.VisibilityOfAllElementsLocatedBy( By.XPath("//*[@id='tve_editor']/div[2]/div[2]/div/div")))

Basic Browser Operations

' Navigate to a page_driver.Navigate().GoToUrl("http://google.com")' Get the title of the pageDim title = _driver.Title' Get the current URLDim url = _driver.Url' Get the current page HTML sourceDim html = _driver.PageSource

Advanced Browser Operations

' Handle JavaScript pop-upsDim a As IAlert = _driver.SwitchTo().Alert()a.Accept()a.Dismiss()' Switch between browser windows or tabsDim windowHandles = _driver.WindowHandlesDim firstTab As String = windowHandles.First()Dim lastTab As String = windowHandles.Last()_driver.SwitchTo().Window(lastTab)' Navigation history_driver.Navigate().Back()_driver.Navigate().Refresh()_driver.Navigate().Forward()' Option 1.link.SendKeys(String.Empty)' Option 2.CType(_driver, IJavaScriptExecutor).ExecuteScript("arguments[0].focus();", link)' Maximize window_driver.Manage().Window.Maximize()' Add a new cookieDim cookie As Cookie = New Cookie("key", "value")_driver.Manage().Cookies.AddCookie(cookie)' Get all cookiesDim cookies = _driver.Manage().Cookies.AllCookies' Delete a cookie by name_driver.Manage().Cookies.DeleteCookieNamed("CookieName")' Delete all cookies_driver.Manage().Cookies.DeleteAllCookies()' Taking a full-screen screenshotDim screenshot As Screenshot = CType(_driver, ITakesScreenshot).GetScreenshot()screenshot.SaveAsFile("pathToImage")' Wait until a page is fully loaded via JavaScriptDim wait As WebDriverWait = New WebDriverWait(_driver, TimeSpan.FromSeconds(30))wait.Until(Function(x) CType(_driver, IJavaScriptExecutor).ExecuteScript("return document.readyState").Equals("complete"))' Switch to frames_driver.SwitchTo().Frame(1)_driver.SwitchTo().Frame("frameName")Dim element = _driver.FindElement(By.Id("id"))_driver.SwitchTo().Frame(element)' Switch to the default document_driver.SwitchTo().DefaultContent()

Advanced Browser Configurations

' Use a specific Firefox profileDim profileManager As FirefoxProfileManager = New FirefoxProfileManager()Dim profile As FirefoxProfile = profileManager.GetProfile("HARDDISKUSER")Dim driver As IWebDriver = New FirefoxDriver(profile)' Set a HTTP proxy FirefoxDim firefoxProfile As FirefoxProfile = New FirefoxProfile()firefoxProfile.SetPreference("network.proxy.type", 1)firefoxProfile.SetPreference("network.proxy.http", "myproxy.com")firefoxProfile.SetPreference("network.proxy.http_port", 3239)Dim driver As IWebDriver = New FirefoxDriver(firefoxProfile)' Set a HTTP proxy ChromeDim options As ChromeOptions = New ChromeOptions()Dim proxy = New Proxy()proxy.Kind = ProxyKind.Manualproxy.IsAutoDetect = Falseproxy.HttpProxy = "127.0.0.1:3239"proxy.SslProxy = "127.0.0.1:3239"options.Proxy = proxyoptions.AddArgument("ignore-certificate-errors")Dim driver As IWebDriver = New ChromeDriver(options)' Accept all certificates FirefoxDim firefoxProfile As FirefoxProfile = New FirefoxProfile()firefoxProfile.AcceptUntrustedCertificates = TruefirefoxProfile.AssumeUntrustedCertificateIssuer = FalseDim driver As IWebDriver = New FirefoxDriver(firefoxProfile)' Accept all certificates ChromeDim capability As DesiredCapabilities = DesiredCapabilities.Chrome()Environment.SetEnvironmentVariable("webdriver.chrome.driver", "C:PathToChromeDriver.exe")capability.SetCapability(CapabilityType.AcceptSslCertificates, True)Dim driver As IWebDriver = New RemoteWebDriver(capability)' Set Chrome options.Dim options As ChromeOptions = New ChromeOptions()Dim dc As DesiredCapabilities = DesiredCapabilities.Chrome()dc.SetCapability(ChromeOptions.Capability, options)Dim driver As IWebDriver = New RemoteWebDriver(dc)' Turn off the JavaScript FirefoxDim profileManager As FirefoxProfileManager = New FirefoxProfileManager()Dim profile As FirefoxProfile = profileManager.GetProfile("HARDDISKUSER")profile.SetPreference("javascript.enabled", False)Dim driver As IWebDriver = New FirefoxDriver(profile)' Set the default page load timeoutdriver.Manage().Timeouts().SetPageLoadTimeout(New TimeSpan(10))' Start Firefox with pluginsDim profile As FirefoxProfile = New FirefoxProfile()profile.AddExtension("C:extensionsLocationextension.xpi")Dim driver As IWebDriver = New FirefoxDriver(profile)' Start Chrome with an unpacked extensionDim options As ChromeOptions = New ChromeOptions()options.AddArguments("load-extension=/pathTo/extension")Dim capabilities As DesiredCapabilities = New DesiredCapabilities()capabilities.SetCapability(ChromeOptions.Capability, options)Dim dc As DesiredCapabilities = DesiredCapabilities.Chrome()dc.SetCapability(ChromeOptions.Capability, options)Dim driver As IWebDriver = New RemoteWebDriver(dc)' Start Chrome with a packed extensionDim options As ChromeOptions = New ChromeOptions()options.AddExtension(Path.GetFullPath("localpathto/extension.crx"))Dim capabilities As DesiredCapabilities = New DesiredCapabilities()capabilities.SetCapability(ChromeOptions.Capability, options)Dim dc As DesiredCapabilities = DesiredCapabilities.Chrome()dc.SetCapability(ChromeOptions.Capability, options)Dim driver As IWebDriver = New RemoteWebDriver(dc)' Change the default files’ save locationDim downloadFolderPath = "c:temp"Dim profile As FirefoxProfile = 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");Dim driver As IWebDriver = New FirefoxDriver(profile)

Online Training

  • NON-FUNCTIONAL

START:13 October 2021

Enterprise Test Automation Framework

LEVEL: 3 (Master Class)

After discussing the core characteristics, we will start writing the core feature piece by piece.
We will continuously elaborate on why we design the code the way it is and look into different designs and compare them. You will have exercises to finish a particular part or extend it further along with discussing design patterns and best practices in programming.

Duration: 30 hours

4 hour per day

-20% coupon code:

BELLATRIX20

About the author

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK