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

Selenium Cheat Sheet

Book for Automation Learning free source
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
204 views

Selenium Cheat Sheet

Book for Automation Learning free source
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 16
sa12ri22, 12:56 PM ‘Selenium cheat sheet — a comprehensive list of selenium commands | by Madan K | Medium Madhan K Apr 17, 2020 - 6 min read y¥oOo8 ¢ + OListe Selenium cheat sheet — a comprehensive list of selenium commands A curated list of selenium commands in Java e 6 e oe e 6 e . J ° * 1, Browser property setup * Chrome: system. setProperty (“webdriver .chrome.driver”, “/path/to/chromedriver”) ; tps 1!medium.com!@machankumaravelug/selenium-cheat-sheeta-comprehensiveslis-otselenium-commans-faécScad! tab#~text-Handle 16 2127122, 12:56 PM. ‘Selenium cheat sheet — a comprehensive list of selenium commands | by Madan K | Medium Firefox: System. setProperty (“webdriver .gecko.driver”,— “/path/to/geckodriver”) ; + Edge: system.setProperty (“webdriver.edge.driver”, “P/path/to/MicrosoftWebDriver”) 5 2. Browser Initialization ° Firefox WebDriver driver = new FirefoxDriver() 5 * Chrome WebDriver driver = new ChromeDriver(); * Internet Explorer WebDriver driver = new InternetExplorerDriver(); Safari Driver WebDriver driver = new SafariDriver(); 3. Desired capabilities (Doc link) * Chrome: DesiredCapabilities caps = new DesiredCapabilities(); caps. setCapabi lity (“browserName”, “chrome”) ; caps.setCapability(“browserVersion”, “80.0””); caps. setCapabi lity (“platformName”, “winl0”) ; WebDriver driver = new ChromeDriver(caps); // Pass the capabilities as an argument to the driver object tps stmedium.com!@machankumaravelu8/selenium-cheat-sheet-a-comprehensiveslis-of-selenium-commands-faécScadt tab#t~text-Handle.. 2/16 2127122, 12:56 PM. ‘Selenium cheat sheet — a comprehensive list of selenium commands | by Madan K | Medium Firefox: DesiredCapabilities caps = new DesiredCapabilities(); caps. setCapabi lity (“browserName”, “firefox”) ; caps. setCapability(“browserVersion”, “81.0””) ; caps.setCapability(“platformName”, “win10”) ; WebDriver driver = new FirefoxDriver(caps); // Pass the capabilities as an argument to the driver object 4. Browser options * Chrome: (Doc link) ChromeOptions chromeOptions = new ChromeOptions() ; chromeOptions.setBinary("C:Program Files (x86) GoogleChromeApplicationchrome.exe"); // if chrome is not in default location chromeOptions.addArguments("--headless");_// Passing single option chromeOpt ions. addArguments ('"--start-maximized", "--incognito","-~ disable-notifications" ); // Passing multiple options WebDriver driver = new ChromeDriver(chromeOptions); // Pass the capabilities as an argument to the driver object © Firefox: (Doc link) FirefoxOptions firefoxOptions = new FirefoxOptions(); firefoxOptions.setBinary(new FirefoxBinary(new File("C:Program FilesMozilla Firefoxirefox.exe"))) ; firefoxOptions.setHeadless(true) ; WebDriver driver = new FirefoxDriver(caps); // Pass the capabilities as an argument to the driver object Options VS Desired capabilities: There are two ways to specify capabilities. 1. ChromeOptions/FirefoxOptions class — Recommended tps smedium.com!@machankumaravelu8/selenium-cheat-sheet-a-comprehensiveslis-ofselenium-commands-faécScadt tab#~text-Handle.. 3/16 sa127i22, 12:56 PM. ‘Selenium cheat sheet — a comprehensive list of selenium commands | by Madan K | Medium 2. Or you can specify the capabilities directly as part of the DesiredCapabilities — its usage in Java is deprecated 5. Navigation * Navigate to URL — (doc link] link2) driver.get(“http://google.com”) driver .navigate(). to(“http: //google. com”) Myth — get() method waits till the page is loaded while navigate() does not. Referring to the selenium official doc, get() method is a synonym for to() method. Both do the same thing. Myth — get() does not store history while navigate() does. All the URLs loaded in the browser will be stored in history and the navigate method allows us to access it. Try executing the below code driver.get(“http: //madhank93.github.io/"); driver.get(“https: //www.google.com/") 5 driver.navigate().back(); * Refresh page driver .navigate().refresh() + Navigate forwards in the browser history driver.navigate() . forward() * Navigate backward in the browser history hitps1!medium.com!@machankumaravelu8/slenium-cheat-sheeta-comprehensiveslis-of-selenium-commands-faécScadt tabi~text-Handle.. 4/16 2127122, 12:56 PM. ‘Selenium cheat sheet — a comprehensive list of selenium commands | by Madan K | Medium driver .navigate() .back() 6. Find element VS Find elements (doc link) © driver.findElement() When no match has found(®) throws NoSuchElementException when 1 match found returns a WebElement instance when 2+ matches found returns only the first matching web element © driver.findElements() when no macth has found (@) returns an empty List when 1 match found returns a list with one WebElement when 2+ matches found returns a list with all matching WebElements 7. Locator Strategy (doc link) ° Byid element = driver. findElement (By. id (“Login”) ) * By Class Name element = driver. findElement (By.className (“Content”) ) ; tps 1!medium.com!@machankumaravelu/selenium-cheat-sheeta-comprehensive-lis-ofselenium-commands-faécScadt tab#~text fandle.. 5/18 2127122, 12:56 PM. ‘Selenium cheat sheet — a comprehensive list of selenium commands | by Madan K | Medium * ByName element = driver. findElement (By.name(“pswd”)) 5 © By Tag Name
Login ‘username"> psw"'> element = driver. findElement (By. xpath(“//input[@placeholder='Username’]”)) ; List of Keywords ~ and, or, contains(), starts-with(), text(), last() * By CSS Selector
element = driver. findElement (By.cssSelector (“input username”) 5 8. Click on an element * click() — method is used to click on an element driver. findELement (By.className("Content")) .click(); 9. Write text inside an element — input and textarea * sendKeys() — method is used to send data driver. findELement (By.className ("email")) .sendkeys (“[email protected]”) 5 10. Clear text from the text box + clear() — method is used to clear text from the text area driver. findELement (By. xpath(‘“//input[@placeholder=’Username’]”)) .clear() 5 11. Select a drop-down (doc link) // single select option // multiple select option * selectByVisibleText() / selectByValue() / selectByIndex() tps 1!medium.com!@machankumaravelu/selenium-cheat-sheeta-comprehensive-lis-ofselenium-commands-faécScadt tab#~text fandle.. 7/8 sa12ri22, 12:56 PM ‘Selenium cheat sheet — a comprehensive list of selenium commands | by Madan K | Medium * deselectByVisibleText() / deselectByValue() / deselectByIndex() // import statements for select class ‘import org.openga.selenium. support.ui.Select; // Single selection Select country = new Select (driver. findElement (By. id ("country") )) ; country. selectByVisibleText ("Canada"); // using selectByVisibleText() method country. selectByValue("MX"); //using selectByValue() method //Selecting Items in a Multiple SELECT elements Select fruits = new Select (driver. findElement (By. id("fruits"))) ; fruits.selectByVisibleText ("Banana") ; fruits.selectByIndex(1); // using selectByIndex() method 12. Get methods in Selenium getTitle() — used to retrieve the current title of the webpage getCurrentUrl() — used to retrieve the current URL of the webpage getPageSource() — used to retrieve the current page source of the webpage getText() — used to retrieve the text of the specified web element getAttribute() — used to retrieve the value specified in the attribute 13. Handle alerts: (Web-based alert pop-ups) driver.switchTO().alert.getText() — to retrieve the alert message » driver.switchTO().alert.accept() — to accept the alert box driver.switchTO().alert.dismiss() — to cancel the alert box driver.switchTO().alert.sendKeys(“Text”) — to send data to the alert box 14, Switch frames + driver.switchTo.frame (int frameNumber) — mentioning the frame index number, the Driver will switch to that specific frame © driver.switchTo.frame(string frameNameOrID) — mentioning the frame element or ID, the Driver will switch to that specific frame hitps1tmedium.com!@machankumaravelu83/slenium-cheat-sheet-a-comprehensiveslis-of-selenium-commands-faécScadt tabi#~text-Handle.. 8/16 2127122, 12:56 PM. ‘Selenium cheat sheet — a comprehensive list of ium commands | by Madhan K | Medium * driver.switchTo.frame(WebElement frameElement) — mentioning the frame web element, the Driver will switch to that specific frame driver.switchTo().defaultContent() — Switching back to the main window 15. Handle multiple windows and tabs * getWindowHandle() — used to retrieve the handle of the current page (a unique identifier) + getWindowHandles() — used to retrieve a set of handles of the all the pages. available © driver.switchTo().window(“windowName/handle”) — switch to a window © driver.close() — closes the current browser window 16. Waits in selenium There are 3 types of waits in selenium, + Implicit Wait — used to wait for a certain amount of time before throwing an exception driver .manage().timeouts().implicitlyWait(10, TimeUnit. SECONDS) ; + Explicit Wait— used to wait until a certain condition occurs before executing the code. WebDriverwait wait = new WebDriverWait (driver ,30) ; wait until (ExpectedCondi tions. presenceOfELementLocated (By .name(""logi nny) List of explicit wait: alertIsPresent() elementSelectionStateToBe() elementToBeClickable() elementToBeSelected() frameToBeAval iableAndSwitchToTt () hitptmedium.conv@madhankumaravelu8sselenium-cheat sheet-a-comprehensiveist-otseenium-commancs-faécSc8dttabi~text"Handle... 116 2127122, 12:56 PM. ‘Selenium cheat sheet — a comprehensive list of selenium commands | by Madan K | Medium invisibilityOfTheElementLocated() ‘invisibilityOfElementWithText () presenceOfALLELementsLocatedBy() presenceOfELementLocated() textToBePresentInElement() textToBePresentInELementLocated() textToBePresentInELementValue() titlels() titleContains() visibilityof() ibilityOfAllELements() visibilityOfAlLELementsLocatedBy () visibilityOfElementLocated() + Fluent Wait — defines the maximum amount of time to wait for a certain condition to appear Wait wait = new FluentWait(WebDriver reference) .withTimeout (Duration.ofSeconds (SECONDS) ) -poLlingEvery (Duration.ofSeconds (SECONDS) ) «ignoring (Exception.class) ; WebElement foo=wait.until(new Function() { public WebElement apply(WebDriver driver) { return driver. findElement (By.id("foo")) ; + Ds 17. Element validation + isEnabled() — determines if an element is enabled or not, returns a boolean. + isSelected() — determines if an element is selected or not, returns a boolean. + isDisplayed() — determines if an element is displayed or not, returns a boolean. 18. Handling proxy * Chrome: ChromeOptions options = new Chromedptions(); // Create object Proxy class - Approach 1 Proxy proxy = new Proxy(); proxy. setHttpProxy ("username: password .myhttpproxy:3337") ; tps 1tmedium.com!@machankumaravelu/selenium-cheat-sheeta-comprehensiveslis-of-selenium-commands-faécSc@dt tabi#~text-Handl... 10/16 2127122, 12:56 PM. ‘Selenium cheat sheet — a comprehensive list of selenium commands | by Madan K | Medium // register the proxy with options class - Approach 1 options. setCapability("proxy", proxy); // Add a ChromeDriver-specific capability. ChromeDriver driver = new ChromeDriver (options) ; « Firefox: FirefoxOptions options = new FirefoxOptions(); // Create object Proxy class - Approach 2 Proxy proxy = new Proxy(); proxy. setHttpProxy ("myhttpproxy:3337") ; proxy.setSocksUsername("username") ; proxy.setSocksPassword ("password") // register the proxy with options class - Approach 2 options. setProxy (proxy) ; // create object to firefx driver WebDriver driver = new FirefoxDriver (options) ; 19. Window management © Get window size: //Access each dimension individually ‘int width = driver.manage() .window() .getSize() .getWidth() ; int height = driver.manage().window().getSize().getHeight(); //Or store the dimensions and query them later Dimension size = driver .manage() .window() .getSize(); ‘int width1 = size.getwidth(); ‘int heightl = size.getHeight(); * Set window size: driver .manage() .window() .setSize(new Dimension(1024, 768)); + Get window position: tps stmedium.com!@machankumaravelu8/selenium-cheat-sheet-a-comprehensiveslis-of-selenium-commands-faécScadt tabi~text-Handl... 11/16 2127122, 12:56 PM. ‘Selenium cheat sheet — a comprehensive list of selenium commands | by Madan K | Medium // Access each dimension individually ‘int x = driver.manage() .window().getPosition().getX(); int y = driver.manage() .window() .getPosition().getY(); // Or store the dimensions and query them later Point position = driver.manage() .window() .getPosition(); int x1 = position. getX(); ‘int yl = position.gety(); * Set window position: // Move the window to the top left of the primary monitor driver.manage() .window() .setPosition(new Point(@, 0)); * Maximize window: driver .manage() .window() .maximize(); ¢ Fullscreen window: driver .manage() .window() .fullscreen() ; 20. Page loading strategy The document. readystate property of a document describes the loading state of the current document. By default, WebDriver will hold off on responding to a driver.get() (or) driver.navigate().to() call until the document ready state is complete By default, when Selenium WebDriver loads a page, it follows the normal pageLoadStrategy. * normal: ChromeOptions chromeOptions = new ChromeOptions(); chromeOpt ions. setPageLoadStrategy (PageLoadStrategy .NORMAL) ; hitps1!medium.com!@machankumaravelu8/selenium-cheat-sheeta-comprehensiveslis-ofselenium-commands-faécScddt tabi#~text fandl.. 128 2127122, 12:56 PM. ‘Selenium cheat sheet — a comprehensive list of selenium commands | by Madan K | Medium WebDriver driver = new ChromeDriver (chromeQptions) ; * eager: When setting to eager, Selenium WebDriver waits until DOMContentLoaded event fire is returned. ChromeOptions chromeOptions = new ChromeOptions(); chromeOpt ions . setPageLoadStrategy (PageLoadStrategy. EAGER) ; WebDriver driver = new ChromeDriver (chromeOptions) ; + none: When set to none Selenium WebDriver only waits until the initial page is downloaded. ChromeOptions chromeOptions = new Chromedptions() ; chromeOptions. setPageLoadStrategy (PageLoadStrategy .NONE) ; WebDriver driver = new ChromeDriver (chromeOptions) ; 21. Keyboard and Mouse events Action class is used to handle keyboard and mouse events keyboard events: * keyDown() + keyUp0 + sendKeys() Mouse events: Openinapp 7” Sign In Q COUDIETHICRY dragAndDrop(source,target) dragAndDropBy(source,xOffset yOffset) moveByOffset(xOffset,yOffset) tps 1!medium.com!@machankumaravelu/selenium-cheat-sheeta-comprehensive-lis-ofselenium-commands-faécScadt tab#~text fandl.. 13/18 2127122, 12:56 PM. ‘Selenium cheat sheet — a comprehensive list of ium commands | by Madhan K | Medium * moveByElement() * release() Actions builder = new Actions(driver) ; Action actions = builder -moveToElement ("Login-textbox") click() -keyDown("Login-textbox", Keys.SHIFT) -sendKeys(""login-textbox", "hello") -keyUp("login-textbox", Keys. SHIFT) -doubLeClick("Login-textbox") contextClick() -build() 5 actions.perform() ; 22. Cookies * addCookie(arg) driver .manage() .addCookie(new Cookie("foo", "bar")); * getCookies() driver manage() .getCookies(); // to get all cookies * getCookieNamed() 439 driver .manage() .getCookieNamed(" foo! + deleteCookieNamed() driver.manage() .deleteCookieNamed ("foo") ; tps stmedium.com!@machankumaravelu/selenium-cheat-sheeta-comprehensiveslis-of-selenium-commands-faécSc@dt tabi~text-Handl... 14/16 2127122, 12:56 PM. ‘Selenium cheat sheet — a comprehensive list of ium commands | by Madhan K | Medium * deleteCookie() Cookie cookiel = new Cookie("test2", "cookie2") ; driver .manage() .addCookie(cookiel) ; driver.manage() .deleteCookie(cookiel); // deleting cookie object © deleteAllCookies() driver .manage() .deleteAllCookies(); // deletes all cookies 23, Take screenshot: (doc link) * getScreenshotAs — used to Capture the screenshot and store it in the specified location. This method throws WebDriverException. copy() method from the File Handler class is used to store the screenshot in a destination folder TakesScreenshot screenShot =(TakesScreenshot)driver; FileHandler . copy (screenShot .getScreenshotAs (OutputType.FILE), new File("path/to/destination/folder/screenshot.png")) 24. Execute Javascript: (doc link) * executeAsyncScript() — executes an asynchronous piece of JavaScript * executeScript() — executes JavaScript if (driver instanceof JavascriptExecutor) { ((JavascriptExecutor) driver) .executeScript ("alert (‘hello world") ;") 5 } hitps1tmedium.com!@machankumaravelu/selenium-cheat-sheet-a-comprehensiveslis-of-selenium-commands-faécSc@dt tabi~text-Handl... 15/16 sa12ri22, 12:56 PM ‘Selenium cheat sheet — a comprehensive list of selenium commands | by Madan K | Medium Last updated on — Apr 18, 2020 madhank93/selenium-cheatsheet-java A comprehensive list of selenium commands in Java. Contribute to madhank93/selenium-cheatsheet-java development by... github.com| References: [1] https://www.selenium.dev/selenium/docs/api/java/overview-summary.html [2] https://www.selenium.dev/documentation/en/ Selenium Cheatsheet Automation Software CPs ee tps 1tmedium.com!@machankumaravelu8/selenium-cheat-sheeta-comprehensiveslis-of-selenium-commands-faécSc@dt tabi#~text-Handl... 16/16

You might also like