Comprehensive Selenium WebDriver Syntax for Effective Test Automation

Comprehensive Selenium WebDriver Syntax for Effective Test Automation



public static void main(String[] args) throws InterruptedException, IOException {

System.setProperty("webdriver.chrome.driver", "./Drivers/chromedriver.exe");

WebDriver driver = new ChromeDriver();

driver.manage().window().maximize();

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

driver.get("https://www.w3schools.com/html/html5_draganddrop.asp");



//Actions MouseOver

WebElement src=driver.findElement(By.xpath("//input[@id='name']"));

WebElement trg=driver.findElement(By.xpath("//input[@id='city']"));

Actions action=new Actions(driver);

action.dragAndDrop(src,trg).build().perform();

action.contextClick(src).build().perform();

action.moveToElement(src).build().perform();



//DropDown

WebElement country=driver.findElement(By.xpath("//input[text()='country']"));

Select dropdown=new Select(country);

dropdown.selectByIndex(2);

dropdown.selectByValue("ind");

dropdown.selectByVisibleText("India");


//ScreenShot

File screen=((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);

FileUtils.copyFile(screen,new File("./photo/image.png"));


//Alert

WebElement alertButton = driver.findElement(By.id("alertButton"));

alertButton.click();

Alert alert=driver.switchTo().alert();

alert.accept();

alert.dismiss();

alert.getText();


//JavaScriptExecutor

JavascriptExecutor js=(JavascriptExecutor)driver;

js.executeScript("window.scrollBy(0,4000)");


//Frame

driver.switchTo().frame(0);

driver.switchTo().frame("Name/Id");

driver.switchTo().frame("WebElement");


//Navigate

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

driver.navigate().forward();

driver.navigate().back();

driver.navigate().refresh();


//Get URL

driver.get("Url");

driver.getCurrentUrl();


//ImplicitilyWait Wait

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


//Explicit wait

WebDriverWait wait=new WebDriverWait(driver,30);

wait.until(ExpectedConditions.titleContains("Webpage | Page"));


//Link on Page

List<WebElement>link=driver.findElements(By.tagName("a"));

for(WebElement links: link){

String text =links.getText();

String href=links.getAttribute("href");

System.out.println(text);

System.out.println(href);

}


//Driver

driver.findElement(By.id("")).sendKeys("");

driver.findElement(By.id("name")).clear();

driver.findElement(By.id("name")).click();


//Excel Reader

String Doc="./TestData/data.xlsx";

FileInputStream fis=new FileInputStream(Doc);

XSSFWorkbook workbook=new XSSFWorkbook(fis);

XSSFSheet sheet=workbook.getSheetAt(0);

String CellValue=sheet.getRow(0).getCell(0).getStringCellValue();

System.out.println(CellValue);


//Without sendKeys()

JavascriptExecutor jss =(JavascriptExecutor)driver;

jss.executeScript("Document.getElementId('usrname').value='masum';");


//git branch --set-upstream-to=origin/master

https://github.com/naveenanimation20/Aug2023SelenoumSessions.git practice


//Mouse Over

Actions action=new Actions(driver);

action.dragAndDrop(src,trg).build().perform();

action.doubleClick(src).build().perform();

action.contextClick(src).build().perform();


// DropDown Options

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

Select dropSelect=new Select(country1);

dropSelect.selectByIndex(1);

dropSelect.selectByValue("");

dropSelect.selectByVisibleText("");


// ScreenShot Capture

File screen1=((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);

FileUtils.copyFile(screen1,new File("./Photo/image.png"));


//Alert Popup

Alert alert1=driver.switchTo().alert();

alert1.dismiss();

alert1.accept();

alert1.getText();


//JavaScriptExecutor Scroll By

JavascriptExecutor js=(JavascriptExecutor)driver;

js.executeScript("window.scrollBy(0,1500)");


// Create an instance of JavascriptExecutor

JavascriptExecutor js = (JavascriptExecutor) driver;


// 2. Scroll to the bottom of the page

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


// 3. Scroll to a specific element

WebElement specificElement = driver.findElement(By.id("specificElementId"));

js.executeScript("arguments[0].scrollIntoView(true);", specificElement);


// 4. Click an element using JavaScript

WebElement clickElement = driver.findElement(By.id("clickElementId"));

js.executeScript("arguments[0].click();", clickElement);


// 11. Disable an element (e.g., a button)

WebElement disableElement = driver.findElement(By.id("disableElementId"));

js.executeScript("arguments[0].setAttribute('disabled', 'true')", disableElement);


// 12. Retrieve the value of a hidden element

WebElement hiddenElement = driver.findElement(By.id("hiddenElementId"));

String hiddenValue = js.executeScript("return arguments[0].value;", hiddenElement).toString();

System.out.println("Hidden Element Value: " + hiddenValue);


Ques. To verify if a logo (or any image) is properly loaded on a webpage

// Find the logo element by its locator (change the locator to match your logo)

WebElement logo = driver.findElement(By.id("logoId"));

boolean isLogoDisplayed = logo.isDisplayed();

boolean hasValidDimensions = (logo.getSize().getHeight() > 0 && logo.getSize().getWidth() > 0);

if (isLogoDisplayed && hasValidDimensions) {

System.out.println("Logo is properly loaded.");

} else {

System.out.println("Logo is not loaded properly.");

}


//Iframe Function

driver.switchTo().frame(1);

driver.switchTo().frame("name/id");

driver.switchTo().frame("webelement");


//Navigate Function

driver.navigate().back();

driver.navigate().forward();

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

driver.navigate().refresh();


//Delete All cookies

driver.manage().deleteAllCookies();

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

driver.manage().window().maximize();


//ExpiciteWait Wait

WebDriverWait wait2=new WebDriverWait(driver,30);

wait2.until(ExpectedConditions.titleContains("mas"));


//File Reader

String Files="data.xlsx";

FileInputStream fi=new FileInputStream(Files);

XSSFWorkbook workbook2=new XSSFWorkbook(fi);

XSSFSheet sheet2=workbook2.getSheetAt(0);

String CellRowValue=sheet.getRow(0).getCell(0).getStringCellValue();

System.out.println(CellRowValue);


//Without sendKeys()

JavascriptExecutor js=(JavascriptExecutor)driver;

js.executeScript("document.getElementById('name').value='name';");


String MainWindow = driver.getWindowHandle();

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

Iterator<String>li=S1.iterator();

While(li.hasNext()){

String childWindow=li.next();

if(!MainWindow.equalsIgnoreCase(childWindow)){

driver.switchTo().window(childWindow);

driver.close();

}

}

driver.switchTo().window(MainWindow);

driver.quit();

}


//To handle multiple windows in Selenium and print the title of the second window

String mainWindowHandle = driver.getWindowHandle();

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

for (String windowHandle : allWindowHandles) {

if (!windowHandle.equals(mainWindowHandle)) {

driver.switchTo().window(windowHandle);

System.out.println("Title of the second window: " + driver.getTitle());

driver.close();

}



//Page Factory (POM)

private static void While(boolean hasNext) {}


public class LoginPagesClass() {

private WebDriver driver;

public void loginPage(WebDriver driver){

this.driver=driver;

PageFactory.initElements(driver,this);

}

}

@FindBy

@CacheLookup


//Broken link checker


List<WebElement> links = driver.findElements(By.tagName("a"));

for (WebElement link : links) {

String url= link.getAttribute("href");

HttpURLConnection connection = (HttpURLConnection) new URL(url1).openConnection();

connection.setRequestMethod("HEAD");

connection.connect();

int responseCode = connection.getResponseCode();

if (responseCode >= 400) {

System.out.println(url1 + " is a broken link.");

}

}

// TestNG Group

----------Class---------

import org.testng.annotations.Test;

public class GroupingExample{

@Test(groups = { "sanity" })

public void test1() {

System.out.println("Sanity Test 1");

}


@Test(groups = { "sanity", "regression" })

public void test2() {

System.out.println("Sanity & Regression Test 2");

}


@Test(groups = { "regression" })

public void test3() {

System.out.println("Regression Test 3");

}

}

--------Test Suit-----------

<suite name="TestSuite">

<test name="GroupedTests">

<groups>

<run>

<include name="sanity"/>

</run>

</groups>

<classes>

<class name="GroupingExample"/>

</classes>

</test>

</suite>

Popular posts from this blog

Explore essential Java programs commonly asked in interviews, offering valuable coding insights and practice.

Top 12 Java Programs for Interview with Output (2025 Edition)