top of page

Selenium Cheat Sheet

arrow.png
arrow_edited_edited.jpg

Driver Initiation

Chrome    

WebDriver driver = new ChromeDriver()

Firefox              

WebDriver driver= new FirefoxDriver()

Safari   

WebDriver driver = new SafariDriver()

Internet Explorer 

WebDriver driver= new InternetExplorerDriver()

Selenium Locators

By ID

driver.findElement(By.id("username")).sendKeys("admin")  

By name  

driver.findElement(By.name("pword")).sendKeys("pword123") By classname

driver.findElement(By.className("input")).click();

By tagName

driver.findElement(By.tagName("a")).click();

By xpath

driver.findElement(By.xpath("//input[@attribute='value']"))

driver.findElement(By.xpath("//button[@attribute='value'][2]"))

driver.findElement(By.xpath("//div/div[3]")

driver.findElement(By.xpath("//button[contains(@class,'submit')]"))

driver.findElement(By.xpath("//h3"))

driver.findElement(By.xpath("//*[text()='Log Out']"))

Selenium Locators

By CSS

tagname

driver.findElement(By.cssSelector("h4"))

tagName.classname

driver.findElement(By.cssSelector("button.signIn"))

tagName#id

driver.findElement(By.cssSelector("input#Username"))

parenttagname childtagname

driver.findElement(By.cssSelector("div[class='login'] h2"))

driver.findElement(By.cssSelector("input[type*='pass']"))

tagName[attribute='value']

tagName[attribute='value']:nth-child(3)

By linkText

driver.findElement(By.linkText("click here"))

By partialLinkText

driver.findElement(By.partialLinkText("Register"))

 Selenium Grid

Start hub

java-jar selenium-server.standalone-<version>.jar-role hub

Start node

java-jar selenium-server-standalone-<version>.jar-role node-hub

Server

http//localhost:4444/grid/register

Configure nodes

-browser browserName=firefox,version=4,

maxInstances=4, platform=WINDOWS

WebDriver Wait

driver.manage().timeouts().implicitlyWait(10,TimeUnit.SECONDS) ;

WebDriverWait wait=new WebDriverWait(driver, 20);

wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(" ")).click()

Browser Navigation

To Launch URL

driver.get("https://www.flipkart.com/")

driver.navigate().to("https://www.flipkart.com/")

To Refresh the page

driver.navigate().refresh()

driver.get(driver.getCurrentUrl());

driver.findElement(By.name("q")).sendKeys(Keys.F5);

JavascriptExecutor js = (JavascriptExecutor) driver;

js.executeScript(“location.reload()”);

js.executeScript(“history.go(0)”);

To navigate forward in browser history

driver.navigate().forward()

To navigate backward in browser history

driver.navigate().back()

Static Dropdown

WebElement  staticdropdown

                                =driver.findElement(By.id("  ")

Select dropdown=new Select(staticdropdown)

dropdown.selectByIndex(3);

dropdown.getFirstSelectedOption().getText(); 

dropdown.selectByVisibleText("AED");

dropdown.getFirstSelectedOption().getText();

dropdown.selectByValue("INR");

dropdown.getFirstSelectedOption().getText();

Dynamic Dropdown

Autosuggestive dropdown

List<WebElement> dynamdd

                              =driver.findElements(By.id("  "));

for( WebElement i:Autosuggestivedropdown) {

     if (i.getText().equalsIgnoreCase("India")) {

              i.click();

                   break; }}

Alerts/Window Handles

driver.switchTo().alert.accept();

driver.switchTo().alert.desmiss();

driver.switchTo().alert.getText();

driver.switchTo().alert.sendKeys("Hello");

Set<String> handles=driver.getWindowhandles();

//Get URL of a currentpage
driver.getCurrentUrl();
//Get the Title of a webpage
driver.getTitle();

Selenium

Execute JavaScript through Selenium WeBdriver

JavascriptExecutor js=(JavascriptExecutor)driver;
//to click a button
js.executeScript(“document.getElementByID(‘element id ’).click();”);
js.executeScript("arguments[0].click();", WebElement);
//to send text
js.executeScript(“document.getElementByID(‘element id ’).value = ‘xyz’;”);
//Scroll window by 
js.executeScript("window.scrollBy(0,500)");

webElement element = driver.findElement(By.xpath("//input[@class='name']"));

js.executeScript("arguments[0].scrollIntoView( );",element);
//to scroll down to the bottom of a webpage
js.executeAsyncScript("window.scrollBy(0,document.body.scrollHeight)");
//Scroll to particular element
js.executeScript("document.querySelector('.table').scrollTop=5000");
//to refresh window
js.executeScript(“location.reload()”);
js.executeScript(“history.go(0)”);
To select checkbox
js.executeScript(“document.getElementByID(‘element id ’).checked=false;”);
//call executeAsyncScript() method to wait for 3 seconds
js.executeAsyncScript(“window.setTimeout(arguments[arguments.length — 1], 3000);”)
//To get the URL of a webpage
js.executeScript(“return document.URL;”).toString();
To find hidden element:
js.executeScript(“arguments[0].click();”, element);
//To navigate to different page:
js.executeScript(“window.location = ‘pageUrl’”);
To select option from dropdown list:
// set the dropdown value to ‘USA’ using javascript
js.executeScript(“arguments[0].value=’USA’”, driver.findElements(By.xpath("//input[@id='country-name']");

//Get the Title of a webpage
js.executeScript(“return document.title;”).toString();

//Get the domain
js.executeScript(“return document.domain;”).toString();

To click on a SubMenu which is only visible on mouse hover on Menu:
js.executeScript(“$(‘ul.menus.menu-secondary.sf-js-enabled.sub-menu li’).hover()”);

To handle Datepickers
WebElement datePicker = driver.findElement(By.xpath("//input[@id='date-field']"));          
       // Remove readonly HTML attribute  
  js.executeScript("document.getElementById('date-field')).removeAttribute('readonly');", datePicker);
datePicker.clear();
            // Enter Date into the field
  driver.findElement(By.xpath("//input[@id='date-field']")).sendKeys("02-01-2008");      
  }

                                         Selenium 4 Relative Locators

//Above Locator
WebElement password = driver.findElement(By.id("password"));
WebElement username = driver.findElement(with(By.tagName("input")).above(password));

//Below Locator
WebElement username = driver.findElement(By.id(“uname"));
WebElement password = driver.findElement(with(By.tagName("input")).below(username));

//LeftOf
WebElement acceptBtn = driver.findElement(By.id(“acceptbtn"));
WebElement cancelBtn =driver.findElement(with(By.tagName(“cancelbtn")).toLeftOf(acceptBtn));

//RightOf
WebElement cancelBtn = driver.findElement(By.id(“cancelbtn"));
WebElement acceptBtn =driver.findElement(with(By.tagName(“acceptbtn")).toRightOf(cancelBtn));

//near
WebElement usernamelbl = driver.findElement(By.id("lbl-uname"));
WebElement username = driver.findElement(with(By.tagName("input")).near(usernamelbl));

//A new window is opened and switches to it
driver.switchTo().newWindow(WindowType.WINDOW);

// A new tab is opened and switches to it
driver.switchTo().newWindow(WindowType.TAB);

Get Screenshot

                        WebElement link = driver.findElement(By.tagName("a"));

                        File f = link.getScreenshotAs(OutputType.FILE);

                        FileUtils.copyFile(f, new File("img.png"));

                                                                 Lambda expressions

Lambda expressions were introduced in Java 8 and are a powerful tool for functional programming. They can be used to simplify code and make it more concise.  It is an anonymous function that can be passed around as an object. It is a concise way to write an inline function.

              (x, y) -> x + y, In this one lambda expression takes two arguments, x and y, and returns the sum of those arguments.

Lambda expressions can be used in a variety of places, such as:

Method arguments:

Lambda expressions can be passed as arguments to forEach methods that accept functions as parameters.

               List<Integer> li=Arrays.asList(85, 19, 21,56);

              li.stream().sorted().forEach(n->{System.out.println(n);});

Lambda expressions has been passed as arguments to forEach method

Collections

Lambda expressions can be used to filter, map, and reduce collections.

      String[] places = { "Canada", "India", "Singapore", "USA", "Spain" , "Iran", "Italy", "Indonesiya"};

      List<String> myplaces = Arrays.asList(places);

      myplaces.stream().filter((p) -> p.startsWith("S")).map((p) -> p.toUpperCase())

.sorted().forEach((p) -> System.out.println(p));

Stream API

Lambda expressions can be used to process streams of data.

myplaces.stream().map((p) -> p.toUpperCase()).forEach((p) -> System.out.println(p));

bottom of page