Selenium-Java Cheat Sheet

Driver setup:

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

Chrome:

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

To download: Visit Here

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

Safari:

SafariDriver now requires manual installation of the extension prior to automation

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");

or

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


To Auto Download in Chrome:

HashMap<String, String> prefs = new HashMap<String, String>();
prefs.put("download.default_directory", "/data/FolderToDownload");


ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.setExperimentalOption("prefs",prefs);

ChromeDriver driver = new ChromeDriver(chromeOptions);

To Auto Download in Firefox:

FirefoxProfile firefoxProfile = new FirefoxProfile();

firefoxProfile.setPreference("browser.download.folderList", 2);
firefoxProfile.setPreference("browser.download.manager.showWhenStarting", false);
firefoxProfile.setPreference("browser.download.dir", "/data/WorkArea/FolderToDownload");
firefoxProfile.setPreference("browser.helperApps.neverAsk.saveToDisk""application/vnd.ms-excel,application/csv,application/vnd.key,application/zip,application/pdf,application/xml");
firefoxProfile.setPreference("pdfjs.disabled", true);

FirefoxOptions firefoxOptions = new FirefoxOptions();
firefoxOptions.setProfile(firefoxProfile);
	
FirefoxDriver driver = new FirefoxDriver(firefoxOptions);

We can add any MIME types in the list

Note:

The value of browser.download.folderList can be set to either 0, 1, or 2. 

0 - Files will be downloaded on the user's desktop. 

1 - Files will be downloaded in the Downloads folder.

2 - Files will be stored on the location specified for the most recent download

Private browser in Firefox:

FirefoxProfile firefoxProfile = new FirefoxProfile();

firefoxProfile.setPreference("browser.privatebrowsing.autostart", true);

firefoxOptions.setProfile(firefoxProfile);

Note: you may not see any indication that browser is private. To check, type 'about:config' and search for 'browser.privatebrowsing.autostart'

Disable notifications in Firefox

firefoxOptions.addPreference("dom.webnotifications.serviceworker.enabled", false);

firefoxOptions.addPreference("dom.webnotifications.enabled", false);


Read Browser Details:

driver.getTitle();

driver.getWindowHandle();

driver.getWindowHandles();

driver.getCurrentUrl();

driver.getPageSource();

Go to a specified URL:

driver.get("https://google.com")

driver.navigate().to("https://google.com")

driver.navigate().to(new URL("https://google.com"))

driver.navigate().back()

driver.navigate().forward()

driver.navigate().refresh()

Locating Elements:

driver.findEelement(By) - To find the first element matching the given locator argument. Returns a WebElement

driver.findElements(By) - To find all elements matching the given locator argument. Returns a list of WebElement

By ID

<input id="q">...</input>

WebElement element = driver.findElement(By.id("q"))

By Name

<input id="q" name="search" type="text"/>

WebElement element = driver.findElement(By.name("search"));

By Class Name

<div class="username" style="display: block; ">...</div>

WebElement element = driver.findElement(By.className("username"));

By Tag Name

<div class="username" style="display: block; ">...</div>

WebElement element = driver.findElement(By.tagName("div"));

By Link Text

<a href="#">Refresh</a>

WebElement element = driver.findElement(By.linkText("Refresh"));

By Partial Link Text

<a href="#">Refresh Here</a>

WebElement element = driver.findElement(By.partialLinkText("Refresh"));

By XPath

<form id="testform" action="submit" method="get">

Username: <input type="text"/>

Password: <input type="password"/>

</form>

WebElement element = driver.findElement(By.xpath("https://form[@id='testform']/input[1]"));

By CSS Selector

<form id="testform" action="submit" method="get">

<input class="username" type="text"/>

<input class="password" type="password"/>

</form>

 WebElement element = driver.findElement(By.cssSelector("form#testform>input.username"));


Element's operation:

button/link/image:

click()

getAttribute()

isDisplayed()

isEnabled()


text field:

sendKeys()

clear()


Checkbox/Radio:

isSelected()

click()


Select:

Select select = new Select(WebElement);

select.selectByIndex();

select.selectByValue();

select.selectByVisibleText();


select.deselectAll();

select.deselectByIndex();

select.deselectByValue();

select.deselectByVisibleText();


getFirstSelectedOption()

getAllSelectedOptions() - Returns List<WebElement>


Element properties:

isDisplayed()

isSelected()

isEnabled()


Read Attribute:

getAttribute("<attribute name>")

Get attribute from a disabled text box 

driver.findElement(By).getAttribute("value");


Screenshot:

image storage without using any extra libraries

TakesScreenshot takeScreenshot = (TakesScreenshot) driver;

File file = takeScreenshot.getScreenshotAs(OutputType.FILE);

FileInputStream fis = new FileInputStream(file);
FileOutputStream fos = new FileOutputStream(new File(System.getProperty("user.dir")+"/test.jpg"));

int cursor;
while((cursor=fis.read())!=-1) {
	fos.write(cursor);
}
fos.close();
fis.close();


Universal Wait:

WebDriverWait webDriverWait = new WebDriverWait(driver, seconds);

webDriverWait.until(new ExpectedCondition<Boolean>() {
	public Boolean apply(WebDriver webDriver) {
		return ((JavascriptExecutor) webDriver)
				.executeScript("return document.readyState").toString().equals("complete");
	}
});

Wait using jQuery:

WebDriverWait webDriverWait = new WebDriverWait(driver, seconds);

webDriverWait.until(new ExpectedCondition<Boolean>() {
	public Boolean apply(WebDriver webDriver) {
		if((Boolean)((JavascriptExecutor)webDriver).executeScript("return window.jQuery != undefined ")) {
			return ((Long) ((JavascriptExecutor) webDriver).executeScript("return jQuery.active") == 0);
		} else {
			return true;
		}
	}
});

Note: jQuery must be defined in Web page otherwise WebDriverException will be thrown. Hence first validate jQuery is defined then check for async calls

The list here contains mostly used features but not exhaustive. Please feel free to add in comments if you feel something is missing and should be here.

For more details - Selenium Java Cheat Sheet and Selenium Python Cheat Sheet

要查看或添加评论,请登录

Arunkumar Velusamy的更多文章

社区洞察

其他会员也浏览了