Selenium Syntax for WebDriver Methods

November 21, 2023
selenium webdriver methods

1. Launching an Empty Firefox Browser with Selenium

Instantiating a new FirefoxDriver object in your Selenium script will launch a fresh instance of the Firefox browser. This newly opened browser window will be empty, meaning it won’t have any pre-loaded pages or tabs.

WebDriver driver = new FirefoxDriver();

2. Execute a Command to Open URL in Browser

driver.get(“http://selenium-suresh.blogspot.com”);

3. Performing click actions on interactive components of a web page

driver.findElement(By.id(“id of any element or button”)).click();

4. Gather the text content of a targeted element and save it in a variable

String suresh = driver.findElement(By.tagName(“select”)).getText();

5. Type the text in text box or text area.

driver.findElement(By.name(“txtboxname”)).sendKeys(“My First Name”);

6. Implementing an implicit wait strategy in Selenium WebDriver

This syntax will force webdriver to wait for 15 second if element not found on page of software web application.

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

7. Implementing an explicit wait in Selenium Webdriver

This will wait for till 15 seconds for expected text “Time left: 7 seconds” to be appear on targeted element.

WebDriverWait wait = new WebDriverWait(driver, 15);

wait.until(ExpectedConditions.textToBePresentInElementLocated(By.xpath(“xpathofelement”), “Time left: 7 seconds”));

8. Obtaining the title of the currently active webpage using Selenium WebDriver

driver.getTitle();

9. Obtaining current page URL in Selenium Webdriver

driver.getCurrentUrl();

10. Obtaining domain name using java script executor

JavascriptExecutor javascript = (JavascriptExecutor) driver;

String CurrentURLUsingJS=(String)javascript.executeScript(“return document.domain”);

11. Creating a pop-up alert window using Selenium WebDriver’s JavaScriptExecutor interface

JavascriptExecutor javascript = (JavascriptExecutor) driver;

javascript.executeScript(“alert(‘Test Case Execution Is started Now..’);”);

12. Choosing or unselecting options from a dropdown menu using Selenium WebDriver

Select By Visible Text– It will select value from drop down list using visible text

value = “Audi”.

Select mydrpdwn = new Select(driver.findElement(By.id(“Carlist”)));

mydrpdwn.selectByVisibleText(“Audi”);

Select By Value- It will select value by value = “Italy”.

Select listbox = new Select(driver.findElement(By.xpath(“//select[@name=’FromLB’]”)));

listbox.selectByValue(“Italy”);

Select By Index- It will select value by index= 0(First option).

Select listbox = new Select(driver.findElement(By.xpath(“//select[@name=’FromLB’]”)));

listbox.selectByIndex(0);

Deselect by Visible Text- It will deselect option by visible text = Russia from list box.

Select listbox = new Select(driver.findElement(By.xpath(“//select[@name=’FromLB’]”)));

listbox.deselectByVisibleText(“Russia”);

Deselect by Value- It will deselect option by value = Mexico from list box.

Select listbox = new Select(driver.findElement(By.xpath(“//select[@name=’FromLB’]”)));

listbox.deselectByValue(“Mexico”);

Deselect by Index- It will deselect option by value = Mexico from list box.

Select listbox = new Select(driver.findElement(By.xpath(“//select[@name=’FromLB’]”)));

listbox.deselectByIndex(5);

It will deselect option by Index = 5 from list box.

Deselect All – It will remove all selections from list box of software application’s page.

Select listbox = new Select(driver.findElement(By.xpath(“//select[@name=’FromLB’]”)));

listbox.deselectAll();

isMultiple()-It will return true if select box is multiselect else it will return false

Select listbox = new Select(driver.findElement(By.xpath(“//select[@name=’FromLB’]”)));

boolean value = listbox.isMultiple();

13. Controlling web page navigation using Selenium WebDriver

driver.navigate().to(“http://selenium-suresh.blogspot.com”);

driver.navigate().back();

driver.navigate().forward();

14. Validate the existence of an element on a web page using Selenium WebDriver

Boolean iselementpresent =driver.findElements(By.xpath(“//input[@id=’text2′]”)).size()!= 0;

15. Taking a full-page screenshot of a web page with Selenium WebDriver

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

FileUtils.copyFile(screenshot, new File(“D:\\screenshot.jpg”));

16. Simulating mouse hover actions on web elements in WebDriver

Actions actions = new Actions(driver);

WebElement moveonmenu = driver.findElement(By.xpath(“//div[@id=’menu1′]/div”));

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

17. Managing multiple browser windows in Selenium WebDriver

Get All Window Handles.—This will give you to get window handle and then how to switch from one window to another window.

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

Extract parent and child window handle from all window handles.

String window1 = (String) AllWindowHandles.toArray()[0];

String window2 = (String) AllWindowHandles.toArray()[1];

Use window handle to switch from one window to other window.

driver.switchTo().window(window2);

18. Determine whether an element is interactable or inactive in Selenium WebDriver

boolean fname = driver.findElement(By.xpath(“//input[@name=’fname’]”)).isEnabled(); System.out.print(fname);

19. Integrating TestNG assertions into Selenium WebDriver scripts for effective test verification

assertEquals

Assert.assertEquals(actual, expected);

assertEquals assertion helps you to assert actual and expected equal values.

assertNotEquals

Assert.assertNotEquals(actual, expected);

assertNotEquals assertion is useful to assert not equal values.

assertTrue

Assert.assertTrue(condition);

assertTrue assertion works for boolean value true assertion.

assertFalse

Assert.assertFalse(condition);

assertFalse assertion works for boolean value false assertion.

20. Trigger form submission using the Submit() method in Selenium WebDriver

driver.findElement(By.xpath(“//input[@name=’Company’]”)).submit();

It will submit the form.

21. Managing modal dialogs, confirmation boxes, and input-based popups in Selenium WebDriver

String myalert = driver.switchTo().alert().getText(); To store alert text.

driver.switchTo().alert().accept(); To accept alert.

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

driver.switchTo().alert().sendKeys(“This Is John”); To type text In text box of prompt popup.

22. DRAG and DROP handling

WebDriver d = new FirefoxDriver();

Actions a=new Actions(d);

a.dragAndDrop(d.findElement(By.id(“draggable”)),d.findElement(By.id(“droppable”))).

build().perform;

23. Frames Handling in Selenium Webdriver

To Enter/Select the Frame – driver.switchTo().frame(“frameid/name / index”)

To Exit from Frame – driver.switchTo().defaultContent()

24. CALENDAR popups

driver.findElement(By.id(“calendar_icon1”)).click();

driver.findElement(By.xpath(“//div[@id=’CalendarControl’]/table[tbody[tr[td[text()=’October 2012′]]]]/descendant::a[text()=’5′]”)).click();

25. Simulating a right-click action to access context menus and perform contextual actions in Selenium WebDriver

WebElement parentMenu = driver.findElement(By.linkText(“Tourist Trains”)); Actions act = new Actions(driver); //Create Action object for Driver act.contextClick(parentMenu).build().perform(); //Context Click act.sendKeys(Keys.ARROW_RIGHT).build().perform(); Thread.sleep(1000); act.sendKeys(Keys.ARROW_DOWN).build().perform(); Thread.sleep(1000); act.sendKeys(Keys.ENTER).build().perform();

26. Alternative Browser Option: Internet Explorer

System.setProperty(“webdriver.ie.driver”,”D:l\\browserdrivers\\IEDriverServer.exe”); WebDriver driver =new InternetExplorerDriver();

driver.get(“http://www.google.com”);

27. Alternative Browser Option: Chrome

System.setProperty(“webdriver.chrome.driver”,”D:\\browserdrivers\\Chromedriver.exe”); WebDriver driver = new ChromeDriver();

driver.get(“http://www.google.com”);

28. Employing Auto-IT to automate Windows authentication dialogs and integrating it with Selenium for web automation

Auto-IT code

WinWaitActive(“Authentication Required”)

Send(“admin”)

Send(“{TAB} admin{TAB} {ENTER}”)

Save the file as default save.(Authentication1.exe)

Calling AutoIT .exe file in selenium

Process P = Runtime.getRuntime().exec(“D:\\AUTOIT\\Authentication1.exe”);

29. Downloading File using RobotClass

Robot robot = new Robot();

//it clicks on SaveFile Radio btn

robot.keyPress(KeyEvent.VK_ALT);

robot.keyPress(KeyEvent.VK_S);

robot.keyRelease(KeyEvent.VK_ALT);

robot.keyRelease(KeyEvent.VK_S);

Thread.sleep(2000);

//Clicks on OK btn

robot.keyPress(KeyEvent.VK_ENTER);

robot.keyRelease(KeyEvent.VK_ENTER);

Thread.sleep(2000);

System.out.println(“File downloaded successfully”);

30. File Upload using Selenium WebDriver

WebElement fileInput = driver.findElement(By.xpath(“//input[@type=’file’][@name=’photofile’]”));

fileInput.sendKeys(“C:\\Users\\Public\\Pictures\\Sample Pictures\\Desert.jpg”);

Thread.sleep(5000);

System.out.println(“File uploaded successfully”);

Join QA Training Hub, best Selenium WebDriver Methods Online Training Course. Classes are instructed by real time experts. Internship and training on real time projects is offered.

Leave a Comment