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.setProperty("webdriver.chrome.driver", “"Path To chromedriver");
To download: Visit Here
Firefox:
System.setProperty("webdriver.gecko.driver", "Path To geckodriver");
To download: Visit GitHub
Internet Explorer:
System.setProperty("webdriver.ie.driver", "Path To IEDriverServer.exe");
To download: Visit Here
Edge:
System.setProperty("webdriver.edge.driver", "Path To MicrosoftWebDriver.exe");
To download: Visit Here
Opera:
System.setProperty("webdriver.opera.driver", "Path 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
Great information
Thank you for the share Ivan T.
Good and detailed writeup.
This is what I called expert👏🏻
good post Ivan T. heard about TestMagic?😉