Selenium Cheat Sheet for Java

Selenium Cheat Sheet for Java


For Python version the link is here


Install Java

To install Java go to this link


IDE

You can use any text editor. I recommend Eclipse as it is free and have extensive support. For list of popular editors , this are the links


Download Selenium

Download selenium webdriver in this link


Dirty our hands !


Import Selenium

import org.openqa.selenium.WebDriver;



Browsers support (Firefox , Chrome , Internet Explorer, Edge , Opera)

Driver setup:

Chrome:

System.se­tPr­ope­rty­("we­bdr­ive­r.chrome.d­riv­er", “"Pat­h To­ chromedr­ive­r");

To download: Visit Here


Firefox:

System.se­tPr­ope­rty­("we­bdr­ive­r.g­eck­o.d­riv­er", "­Pat­h To­ g­eck­odr­ive­r");

To download: Visit GitHub


Internet Explorer:

System.se­tPr­ope­rty­("we­bdr­ive­r.ie.d­riv­er", "Pat­h To­ IEDriverServer.exe");

To download: Visit Here

Edge:

System.se­tPr­ope­rty­("we­bdr­ive­r.edge.d­riv­er", "Pat­h To­ MicrosoftWebDriver.exe");

To download: Visit Here


Opera:

System.se­tPr­ope­rty­("we­bdr­ive­r.opera.d­riv­er", "Pat­h To­ operadriver");

To download: visit GitHub

Browser Arguments:

–headless

To open browser in headless mode. Works in both Chrome and Firefox browser

–start-maximized

To start browser maximized to screen. Requires only for Chrome browser. Firefox by default starts maximized

–incognito

To open private chrome browser

–disable-notifications

To disable notifications, works Only in Chrome browser

Example:

ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.addArguments("--headless");
chromeOptions.addArguments("--start-maximized");
chromeOptions.addArguments("--disable-notifications");
chromeOptions.addArguments("--incognito");


Alternative

ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.addArguments("--incognito","--start-maximized","--headless");


Launch URL

driver.get(url)


Retrieve Browser Details:

driver.getTitle();
driver.getWindowHandle();
driver.getWindowHandles();
driver.getCurrentUrl();
driver.getPageSource();


Navigation

driver.get(url);
driver.navigate().to(url);
driver.navigate().to(new URL(url));
driver.navigate().back();
driver.navigate().forward();
driver.navigate().refresh();


Locating Elements

By id

<input id=”login” type=”text” />

element = driver.findElement(By.id(“login”))


By Class Name

<input class=”gLFyf” type=”text” />

element = driver.findElement(By.className(“gLFyf”));


By Name

<input name=”z” type=”text” />

element = driver.findElement(By.name(“z”));


By Tag Name

<div id=”login” >…</div>

element = driver.findElement(By.tagName(“div”));


By Link Text

<a href=”#”>News</a>

element = driver.findElement(By.linkText(“News”));


By XPath

<form id=”login” action=”submit” method=”get”>

Username: <input type=”text” />

Password: <input type=”password” />

</form>

element = driver.findElement(By.xpath(“//form[@id='login']/input”));


By CSS Selector

<form id=”login” action=”submit” method=”get”>

Username: <input type=”text” />

Password: <input type=”password” />

</form>

element = driver.findElement(By.cssSelector("input.username"));


Clicking / Input text

Clicking button

chromedriver.findElement(By.className("gLFyf")).click();


Send Text

chromedriver.findElement(By.className("gLFyf")).send_keys("hello");


Waits

Implicit Waits

An implicit wait instructs Selenium WebDriver to poll DOM for a certain amount of time, this time can be specified, when trying to find an element or elements that are not available immediately.

driver = webdriver.Chrome();
driver.manage().timeouts().implicitlyWait(10,TimeUnit.SECONDS) ;
driver.get("https://www.google.com");
driver.findElement(By.name("q")).click();


Explicit Waits

Explicit wait make the webdriver wait until certain conditions are fulfilled . Example of a wait

new WebDriverWait (chromeDriver,10).until(ExpectedConditions.presenceOfElementLocated(By.name("q")));


List of explicit waits

  • alertIsPresent()
  • elementSelectionStateToBe()
  • elementToBeClickable()
  • elementToBeSelected()
  • frameToBeAvaliableAndSwitchToIt()
  • invisibilityOfTheElementLocated()
  • invisibilityOfElementWithText()
  • presenceOfAllElementsLocatedBy()
  • presenceOfElementLocated()
  • textToBePresentInElement()
  • textToBePresentInElementLocated()
  • textToBePresentInElementValue()
  • titleIs()
  • titleContains()
  • visibilityOf()
  • visibilityOfAllElements()
  • visibilityOfAllElementsLocatedBy()
  • visibilityOfElementLocated()



Loading a list of elements like li and selecting one of the element

 public void test1() {

	  

	  String searchButton_css = "button.btn.Searchbox__searchButton.Searchbox__searchButton--active[data-selenium='searchButton']";

	  String inputDestination_css = "input[data-selenium='textInput']";

	  String suggestedDestinationList_css = "ul.AutocompleteList";

	  String stringBali = "Bali";

	  

	  System.setProperty("webdriver.chrome.driver", "//Users//ivantay//WebDrivers//chrome//mac//chromedriver");

	  driver=new ChromeDriver ();

	  driver.get(url);

	  

	  new WebDriverWait (driver,10).until(ExpectedConditions.presenceOfElementLocated(By.cssSelector(searchButton_css)));

	  driver.findElement(By.cssSelector(inputDestination_css)).sendKeys("Bali Indonesia");

	  

	  new WebDriverWait (driver,10).until(ExpectedConditions.presenceOfElementLocated(By.cssSelector(suggestedDestinationList_css)));

	  WebElement items = driver.findElement(By.cssSelector(suggestedDestinationList_css));

	  List <WebElement> elementsList = items.findElements(By.tagName("li"));

	  

	  for (WebElement item : elementsList){

		  

		  if (item.getText().contains(stringBali)){

			  

			  item.click();

			  break;

		  }

		  

	  }

	  

  }



Read Attribute

System.out.println("Title of searchbar : "+ chromedriver.findElement(By.name("q")).getAttribute("jsaction"));


Get CSS

driver = webdriver.Chrome();

// open website
driver.get("https://google.com");

// get the css value
String cssValue = driver.findElement(By.name("q")).getCssValue("font-size");
System.out.println("font size searchbar : "+ cssValue);

CSS values varies on different browser, you may not get same values for all the browser.


Capture Screenshot

public void captureSnapShot(WebDriver driver,String path) throws Exception{

        //Convert web driver object to TakeScreenshot

        TakesScreenshot scrShot =((TakesScreenshot)driver);

        //Call getScreenshotAs method to create image file

                File srcFile=scrShot.getScreenshotAs(OutputType.FILE);

            //Move image file to new destination

                File destFile=new File(path);

                //Copy file at destination

                FileUtils.copyFile(srcFile, destFile);

    }


This will saved the file as in the path of destFile.


isSelected()

isSelected() method in selenium verifies if an element (such as checkbox) is selected or not. isSelected() method returns a boolean.

driver = webdriver.Chrome();

// open website
driver.get("https://google.com.sg");

// get css value
boolean isSelected = driver.findElement(By.xpath("//input[@id='selected']")).isSelected();
System.out.println("Is checkbox selected : ", isSelected);


isDisplayed()

isDisplayed() method in selenium webdriver verifies and returns a boolean based on the state of the element (such as button) whether it is displayed or not.

driver = webdriver.Chrome();

// open website
driver.get("https://google.com");

// get css value
boolean isDisplayed = driver.findElement(By.name("q")).isDisplayed();
System.out.println("Is Searchbar Displayed : ", isDisplayed);


isEnabled()

is_enabled() method in selenium python verifies and returns a boolean based on the state of the element (such as button) whether it is enabled or not.

driver = webdriver.Chrome();

// open website
driver.get("https://google.com");

// element enabled
boolean isEnabled = driver.findElement(By.name("q")).isEnabled();
System.out.println("Is searchbar enabled : ", isEnabled);

 

Minimum modules to import

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;


Created : 17 December 2019

To view or add a comment, sign in

More articles by Ivan T.

  • Short hiatus (1 month) from social media and its impact

    I am a huge fan of LinkedIn, Instagram, TikTok, YouTube, Reddit, a few e-commerce sites and other popular platforms. I…

    15 Comments
  • Solution Focused - Not Knowing Position

    Solution Focused Brief Therapy (SFBT) is a form of therapy that has gained popularity in recent decades. It is a brief…

    9 Comments
  • Text Counselling

    Why is counselling important for our mental health Counselling is important for mental wellness because it provides a…

    11 Comments
  • Loneliness

    We feel lonely from time to time. The feelings of loneliness are personal, and everyone's experience will differ.

    9 Comments
  • Struggling over popular festive season (Lunar New Year)

    Lunar New Year is this week. It is meant to be a time of joy with celebrations, red envelopes, gifts and qualify family…

    9 Comments
  • Passing data in React between Parent and Child in Functional Components

    For beginners who started out in ReactJS, passing data between components may be confusing. I struggle this when I…

    6 Comments
  • Getting your React project ready for Heroku

    If you are new to React JS and want to deploy to Heroku, these are few steps to ensure that you can deploy…

    3 Comments
  • Console Tricks

    Console is is a favourite feature for many web developers. If you have been using it, you know there are lots of tricks.

    12 Comments
  • Why And How We Should Learn To Say No

    Are you a people pleaser ? Do you find it difficult to say "No" or reject an invitation, task or someone's request ?…

    9 Comments
  • HTTP Status Code

    When we visit a (web) site, it usually send some request to the server. There will be a returned code to indicate the…

    24 Comments

Others also viewed

Explore content categories