Adavantages

Auto-Wait - Built-in smart waits (no need for explicit waits)

Multiple browser contexts - Fast, isolated testing without restarting the browser (without new browser sessions)

Modern Web Support - It supports Single Page Applications.

Built-in Test Runner - Comes with Playwright Test (No need of external runner like TestNG, Junit)

Cross-browser with one API - Chromium, Firefox, WebKit (Safari)

Multiple language bindings - Java Script, Type Script, Python, Java, C#

Parallel test execution - Built in and fast (possible in selenium, but more setup is required)

Visual Comparisions - Supports screen shot testing (Selenium required third party tools)

CI/CD Friendly - CLI tools and trace viewer for debugging (but less built-in tooling for selenium)


Creating new instance of firefox driver 

const { firefox } = require('playwright'); // or 'playwright-core'

(async () => {

  const browser = await firefox.launch({ headless: false }); // headless: false to see the browser

  const context = await browser.newContext();

  const page = await context.newPage();

  await page.goto('https://example.com');

  // Do your testing here...

  await browser.close();

})();


Creating new instance of Chrome driver

const { chromium } = require('playwright');

(async () => {

  const browser = await chromium.launch({

    channel: 'chrome',     // <- this specifies actual Chrome instead of Chromium

    headless: false        // for headed mode

  });


Creating new instance of IE driver

System.setProperty("webdriver.ie.driver", "D:\\....\\IEDriverServer.exe");

WebDriver driver = new InternetExplorerDriver();

Command to open URL in browser 

driver.get("http://www.---.com");

Clicking on an element 

driver.findElement(By.xpath(" ")).click();

Storing text of targeted element in a variable 

String var = driver.findElement(By.id("")).getText();

Typing text in text box

driver.findElement(By.name(" ")).sendKeys("mylastname");

Getting the value from text box

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

Implicit wait 

driver.manage().timeouts().implicityWait(Duration.ofSeconds(10));

Explicit wait 

WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));

wait.until(ExpectedConditions.textToBePresentInElementLocated(By.xpath(""), "Download complete");

alertIsPresent, elementToBeClickable, elementToBeSelected, visibilityof ElementLocated, presenceOfElementLocated

Fluent wait

Wait<WebDriver> wait = new FluentWait<WebDriver>(driver) .withTImeOut(Duation.ofSeconds(10)) .pollingEvery(Duation.ofSeconds(10)) .ignoring(NoSuchElementException.class);

Get page title 

driver.getTitle();

Get Current Page URL 

driver.getCurrentUrl();

Get domain using java script executor 

JavaScriptExecutor executor = (JavaScriptExecutor) driver; 

String currentURL = (String)executor.executeScript("return document.domain");

Generate alert using java script executor 

JavaScriptExecutor executor = (JavaScriptExecutor) driver; 

executor.executScript("alert("Test Case Execution is started now..");");

Selecting or Deselecting value from drop down 

Select drpdwn = new Select(driver.findElement(By.id(" "))); 

drpdwn.(de)selectByVisibleText("Audi"); 

drpdwn.(de)selectByIndex(1); 

drpdwn.(de)selelctByValue("Italy");

Removing all selections from listbox 

Select listbox = new Select(driver.findElement(By.xpath(" "))); listbox.deselectAll();

Checking whether a select box is multiselect 

boolean value = listbox.isMultiple();

Retrieving all values from dropdown

 List<WebElement> options = select.getOptions();

Navigate to backward or forward 

driver.navigate().to(" "); 

driver.navigate().back(); 

driver.navigate().forward();

Refresh the page

driver.navigate.refresh()

Verify whether a element present 

Boolean isElementPresenet = driver.findElements(By.xpath(" ")).size()!=0;

Capturing screenshot 

File screenshot = ((TakesScreenShot)driver).getScreenshotAs(OutputType.FILE);

FileUtils.copyFile(sceenshot, newFile(System.getProperty(user.dir)/ScreenShots);

Generating mouse hover event Actions 

actions = new Actions(driver); 

WebElement menu = driver.findElement(By.xpath(" "));

actions.moveToElement(menu).build().perform();

Handling multiple windows file 


Set<String> AllWindows = driver.getWindowHandles();

String pWindow = (String)AllWindows.toArray()[0]; 

String cWindow = (String)AllWindows.toArray()[1]; 

driver.swithTo().window(cWindow);


String parent=driver.getWindowHandle(); // to get the parent window name

// Now iterate using Iterator

Iterator<String> I1= allWindows.iterator();
while(I1.hasNext())
{

String child_window=I1.next();


if(!parent.equals(child_window))
{
driver.switchTo().window(child_window);

System.out.println(driver.switchTo().window(child_window).getTitle());

driver.close();
}

}

Check whether an element is enabled or disabled 

boolean fname = driver.findElement(By.xpath(" ")).isEnabled();

Assertions with TestNG framework 

Assert.assertEquals(actual, expected) - to assert actual and expected values are equal

 Assert.assertNotEquals(actual, expected) - to assert not equal values

Assert.assertTrue(condition) - works for boolean value true assertion 

Assert.assertFalse(condition) - works for boolean value false assertion

Submitting a form 

driver.findElement(By.xpath(" ")).submit();

Handling alerts String 

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

driver.switchTo().alert().accpet(); 

driver.switchTo().alert().dismiss(); 

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

Handling drag and drop 

Actions ac = new Actions(); 

ac.dragAndDrop(driver.findElement(By.id("draggable"), driver.findElement(By.id("droppable")))).

build.perform();

Handling the frames 

driver.switchTo().frame("frameid/name/index"); //to enter the frame driver.switchTo().defaultContent(); //to exit the frame

Calendar popups 

driver.findElement(By.id("calendar_icon 1")).click();

 driver.findElement(By.xpath("//div[@id='CalendarControl']/table/tbody[tr[td[text()='Octoer 2012']]]] /descendant::a[text()='5'])).click();

Context click (Right Click) 

WebElement parentMenu = driver.findElement(By.linkText("Srinivas")); 

Actions act = new Actions(driver); 

act.contextClick(parentMenu).build().perform();

act.sendKeys(Keys.ARROW_DOWN).build().perform(); 

Thread.sleep(1000); 

act.sendKeys(Keys.ENTER).build().perform();

Auto IT 

WinWaitActivate("Authentication Required") 

Send("admin") Send("{TAB} admin {TAB} {ENTER}") 

Save the file as 'Authentication.exe' 

Calling .exe file in selenium 

Process P = Runtime.getRuntime().exec("D:\\....\\Authentication.exe");

File Download using RobotClass 

Robot robot = new Robot(); 

robot.KeyPress(KeyEvent.VK_ALT); 

robot.KeyPress(KeyEvent.VK_S); 

robot.KeyRelease(KeyEvent.VK_ALT); 

robot.KeyRelease(KeyEvent.VK_S); 

Thread.sleep(2000); 

robot.KeyPress(KeyEvent.VK_ENTER); 

robot.KeyRelease(KeyEvent.VK_ENTER); 

Thread.sleep(2000);

File upload using webDriver 

WebElement fileInput = driver.findElement(By.xpath("//input[@type='file'][@name='photfile']")); fileInput.sendKeys("D:\\.....\\Desert.jpg"); Thread.sleep(2000);

Scrolling 

Actions ac = new Actions(driver); ac.KeyDown(Keys.CONTROL).sendKeys(Keys.HOME).build().perform(); ac.KeyDown(Keys.CONTROL).sendKeys(Keys.END).build().perform(); (OR) WebElement element = driver.findElement(By.xpath("scroll bar locator")); ac.moveToElement(element).clickANDHold().moveByOffset(x,y).release().perform();

Fluent Wait

FluentWait <WebDriver> wait = new FluentWait<WebDriver>(driver) .withTImeOut(30,SECONDS); .pollingEvery(5,SECONDS); .ignoring(NoSuchElementException.class)

Sample X paths

//input[contains[@name,'Name')] 

//input[starts_with(@name, txt')] 

//input[@name = 'txtUserName'] 

//table[@id = 'Table_o1']/tbody/tr/td[2]/input //a[contains(text(), "RRR")]

//h1[normalize-space(text()) = 'Dashboard']

Clicking on web element WebElement element = driver.findElement(By.id("id of webelement")); JavaScriptExecutor js = (JavaScriptExecutor) driver; js.executeScript("arguments[0].click();", element);

Typing in text box js.execteScript("document.getElementById('id of the eleement').value='test data';"); Scrolling down js.executeScript("arguments[0].scrollIntoView(true);", element);

Scroll to an element

((JavascriptExecutor) driver).executeScript(

"arguments[0].scrollIntoView();", element);

Scroll to bottom of the page

((JavascriptExecutor) driver)

.executeScript("window.scrollTo(0, document.body.scrollHeight)");


Scroll to coordinates

((JavascriptExecutor) driver).executeScript("window.scrollBy(0,500)");