info@pragmatictesters.com +94 11 253 8512

Introduction

Using a language effectively could be possible if you have a good vocabulary in your toolbox. Knowing various selenium command, options, limitation, and application are essential for a Selenium test automation engineer to use Selenium effectively in test automation.

In this blog post, we have discussed Selenium commands useful for beginners.

 

WebDriver

Navigate to a URL

You will have to access the system soon after launching a web browser.

Following commands can be used to load a new web page in the current browser window. This is done using an HTTP GET operation, and the method will block until the load is complete.

There are few options available. But driver.get() method is mostly used and the first command learned by the testers.

webDriver.get("http://demosite.pragmatictestlabs.com");
webDriver.navigate.to("http://demosite.pragmatictestlabs.com");
URL BASE_URL= new URL("http://demosite.pragmatictestlabs.com");
webDriver.navigate.to(BASE_URL);
webDriver.Navigate().GoToUrl("http://demosite.pragmatictestlabs.com");
webDriver.Url = "http://demosite.pragmatictestlabs.com";
webDriver.get("http://demosite.pragmatictestlabs.com")
webDriver.navigate.to 'http://demosite.pragmatictestlabs.com'
 

Closing current browser window

It is a good practice to close the browser window(s) opened by the automated tests. Close method in the WebDriver can be used for closing the current window. It will quit the browser if it’s the last window.

NoSuchSessionException will be thrown if any command is called after closing all the windows.

webDriver.close();
webDriver.Close();
webDriver.close()
webDriver.close

Closing all browser instances

Sometimes more than one browser window is opened when test scenarios are executed. You will have to close all the browser windows.WebDriver quit method can be used to close every browser windows  associated with the driver instance.

NoSuchSessionException will be thrown when any command is called after closing all the browser windows.

webDriver.quit();
webDriver.Quit();
webDriver.quit()
webDriver.quit

You may have to simulate shortcut keys to close the browser instance.  Following can be used for closing Opera.

private void closeOperaBrowser(WebDriver webDriver){
    Robot robot = null;
    try {
        robot = new Robot();
    } catch (AWTException e) {
        e.printStackTrace();
    }
    robot.keyPress(KeyEvent.VK_CONTROL);
    robot.keyPress(KeyEvent.VK_SHIFT);
    robot.keyPress(KeyEvent.VK_X);
}

You should call the quit method whenever you want to end the test suite execution. It will close all opened browser window and terminates the WebDriver session. If you do not use quit at the end of program, WebDriver session will not close properly and files would not be cleared off memory. This may result in memory leak errors.

 

Refresh the current browser window

Refresh method of the WebDriver can be used for refreshing the current window.

webDriver.navigate().refresh();
webDriver.Navigate().Refresh();
webDriver.refresh()
webDriver.navigate.refresh

Using sendKeys.Keys method

webDriver.findElement(By.id("txtUsername")).sendKeys(Keys.F5);
webDriver.FindElement(By.Id("passwordTextBox")).SendKeys(Keys.F5);
IWebElement passwordTextBox = webDriver.FindElement(By.Id("passwordTextBox"));
passwordTextBox.SendKeys(Keys.F5);
webDriver.find_element_by_name("passwordTextBox").send_keys(Keys.F5)
elem = webDriver.find_element_by_name("passwordTextBox")
elem.send_keys(Keys.F5)
element1 = webDriver.find_element(:id, 'firstname')
element1.send_keys [:control, 'a']

Using get() method

webDriver.get(webDriver.getCurrentUrl());
webDriver.Url;
webDriver.current_url
webDriver.current_url

Alternatively you could simulate pressing  Ctrl + F5 keys to refresh the browser windows

Robot robot = null;
try {
    robot = new Robot();
} catch (AWTException e) {
    e.printStackTrace();
}
robot.keyPress(KeyEvent.VK_F5);

 

Using sendKeys() method

webDriver.findElement(By.id("txtUsername")).sendKeys("password");
webDriver.FindElement(By.Id("passwordTextBox")).SendKeys("password");
webDriver.find_element_by_name("passwordTextBox").send_keys("password")
element = webDriver.find_element(:id, 'passwordTextBox')
element.send_keys 'password!'

Pressing back button of a web browser

You can simulate clicking the back button in a web browser using back methods. It will back a single “item” in the browser’s history.

webDriver.navigate().back();
webDriver.Navigate().Back();
webDriver.back()  #The back() method is not guaranteed to work.
webDriver.execute_script("window.history.go(-1)") #This is the best solution
webDriver.navigate.back
 

Navigating forward in a web browser

You can simulate clicking the forward button in a web browser using forward methods. Move a single “item” forward in the browser’s history. Does nothing if we are on the latest page viewed.

webDriver.navigate().forward();
webDriver.Navigate().Forward();
webDriver.forward() #The forward() method is not guaranteed to work.
webDriver.execute_script("window.history.go(+1)") #This is the best solution
webDriver.navigate.forward

Get page title

getTitle method can be used to get title of the current page.

webDriver.getTitle();
webDriver.Title;
webDriver.title
webDriver.title

Get current URL

It is possible to get the URL of the currently loaded page using getCurrentUrl method.

webDriver.getCurrentUrl();
webDriver.Url;
webDriver.current_url
webDriver.current_url

Get current page source

Sometimes you may not have a command to extract specific content from a web page. You can get a page source using WebDriver’s getPageSource method and manipulate the source (String) to extract specific content.

webDriver.getPageSource();
webDriver.PageSource;
webDriver.page_source
webDriver.page_source

 

WebElement

Clicking an element

Click method can be used for simulating clicking a given element. You must ensure the element is visible.

webDriver.findElement(By.id("btnLogin")).click();
webDriver.FindElement(By.Id("btnSubmit")).Click();
IWebElement btnSubmit = webDriver.FindElement(By.Id("btnSubmit"));
btnSubmit.Click();
webDriver.find_element_by_id("btnSubmit").click()
btnSubmit= webDriver.find_element_by_id("btnSubmit")
btnSubmit.click()
btnSubmit = webDriver.find_element(:id, 'btnSubmit')
btnSubmit.click

If a new page is loaded reference to the element should be discarded. StaleElementReferenceException is thrown if an element’s methods is called after a new page loading

org.openqa.selenium.StaleElementReferenceException: stale element reference: element is not attached to the page document

The Element Click command scrolls into view the element if it is not already pointer-interactable, and clicks its in-view center point.

If the element’s center point is obscured by another element, an element click intercepted error is returned. If the element is outside the viewport, an element not interactable error is returned.

Enter a string into an input element

Typing text into elements like input and textarea can be simulated using sendKeys method of a WebElement.  sendKeys method will append the text into the existing text.

webDriver.findElement(By.id("txtusername")).sendKeys("Admin");
webDriver.FindElement(By.Id("txtusername")).SendKeys("Admin");
IWebElement username = webDriver.FindElement(By.Id("txtusername"));
username.SendKeys("Admin");
webDriver.find_element_by_id("txtusername").send_keys("Admin")
elem = webDriver.find_element_by_id("txtusername")
elem.send_keys("Admin")
webDriver.find_element(:id, 'txtusername').send_keys 'Admin'
element = webDriver.find_element(:id, 'txtusername')
element.send_keys 'Admin'

If you want to clear the existing string and type new value clear method of the WebElement can be used.

webDriver.findElement(By.id("txtUsername")).clear();
webDriver.findElement(By.id("txtUsername")).sendKeys("Admin");
webDriver.FindElement(By.Id("txtusername")).Clear();
webDriver.FindElement(By.Id("txtusername")).SendKeys("Admin");
elem = webDriver.find_element_by_id("btnSubmit").clear()
elem.send_keys("Admin")
element = webDriver.find_element(:id, 'txtusername') element.clear element.send_keys 'Admin'

If you cannot use the clear method following is an option.

webDriver.findElement(By.id("txtUsername")).sendKeys(Keys.CONTROL + "a");
webDriver.findElement(By.id("txtUsername")).sendKeys("Admin");
webDriver.FindElement(By.Id("txtusername")).SendKeys(Keys.Control + "a");
webDriver.FindElement(By.Id("txtusername")).SendKeys("Admin");
webDriver.find_element_by_id('txtusername').send_keys(Keys.COMMAND + 'a')
webDriver.find_element_by_id('txtusername').send_keys(‘Admin’)
webDriver.find_element(:id, 'txtusername').send_keys [:control, 'a']
webDriver.find_element(:id, 'txtusername').send_keys 'Admin

sendKeys will set the value  attribute of the input element.

Getting text

It may be required to extract the visible text from an element for validation. You can extract the inner text by calling getText method of a WebElement. Leading and trailing spaces are removed.

webDriver.findElement(By.id("welcome")).getText();
webDriver.FindElement(By.id("welcome")).Text;
webDriver.find_element_by_id("welcome").text
webDriver.find_element(:id, welcome).text
getText() cannot be used for extracting String in input element such as input or textarea elements.

Get the value of the given attribute of an element

getAttribute methods can be used to get the value of the given attribute of the element. It will return the value of the property with the given name, if it exists. If it does not, then the value of the attribute with the given name is returned. If neither exists, null is returned.

webDriver.findElement(By.id("txtUsername")).getAttribute("value");
webDriver.FindElement(By.Id("txtUsername")).GetAttribute("value");
webDriver.find_element_by_id("txtusername").get_attribute("value")
webDriver.find_element(:id, 'txtusername').attribute('value')

Clearing text in an input element

You may need to clear the existing text in an input element in a test case. It is always safer to clear an input element before using sendKeys method unless you want to append to the existing content in an input element.

InvalidElementStateException is thrown if the element is not an input element. org.openqa.selenium.InvalidElementStateException: invalid element state: Element must be user-editable in order to clear it.

webDriver.findElement(By.id("txtusername")).clear();
webDriver.FindElement(By.Id("txtusername")).Clear();
webDriver.find_element_by_id("txtusername").clear
webDriver.find_element(:id, 'txtusername').clear

 

Working with Dropdowns

Selecting an item from a list

Selecting an item from a list (dropdown) is handled using Select class. You need to provide the WebElement of dropdown to create a Select object. Select class has got methods to select/deselect a single item or multiple items. It has methods to select/deselect items by index, visible text or value attribute.

 

Selecting an item by index

Select lstStatus = new Select (webDriver.findElement(By.xpath("//select[@id='status']")));
lstStatus.selectByIndex(1);
var lstStatus = webDriver.FindElement(By.XPath("//select[@id='status']"));
var selectElement = new SelectElement(lstStatus);
selectElement.SelectByIndex(1);
selectElement = Select(webDriver.find_element_by_id("//select[@id='status']") )
selectElement .select_by_index(1)
select_list = Selenium::WebDriver::Support::Select.new(webDriver.find_element(xpath: '//select[@id='status']'))
select_list.select_by(:index, '1')

Index is zero based. Hence the second item in the list will be selected when index 1 is given.

NOTE : NoSuchElementException will be thrown if matching element is not available for select and deselect options.

Selecting item(s) by visible text

All the options with given (visible) text will be selected.

Select lstStatus = new Select (webDriver.findElement(By.xpath("//select[@id='status']")));
lstStatus.selectByVisibleText("Disabled");
var lstStatus = webDriver.FindElement(By.XPath("//select[@id='status']"));
var selectElement = new SelectElement(lstStatus);
selectElement.SelectByText("Disabled");
selectElement = Select(webDriver.find_element_by_id("//select[@id='status']") )
selectElement .select_by_visible_text('Disabled')
select_list = Selenium::WebDriver::Support::Select.new(webDriver.find_element(xpath: '//select[@id='status']'))
select_list.select_by(:text, 'Disabled')

Selecting item(s) by value

Select all options that have a value matching the argument

Select lstStatus = new Select (webDriver.findElement(By.xpath("//select[@id='status']")));
lstStatus.selectByValue("Disabled")
var lstStatus = webDriver.FindElement(By.XPath("//select[@id='status']"));
var selectElement = new SelectElement(lstStatus);
selectElement.SelectByValue("Disabled");
selectElement = Select(webDriver.find_element_by_id("//select[@id='status']") )
selectElement .select_by_value('Disabled')
select_list = Selenium::WebDriver::Support::Select.new(webDriver.find_element(xpath: '//select[@id='status']'))
select_list.select_by(:value, 'Disabled')

 

Deselecting items from a list

Deselecting an item by index

It is possible to deselect an option by giving their position. Index is zero based.

Select lstStatus = new Select (webDriver.findElement(By.xpath("//select[@id=’cars’]")));
lstStatus.deselectByIndex(1);
var lstStatus = webDriver.FindElement(By.XPath("//select[@id=’cars’]"));
var selectElement = new SelectElement(lstStatus);
selectElement.DeselectByIndex(1);
selectElement = Select(webDriver.find_element_by_id("//select[@id=’cars’]") )
selectElement.deselect_by_index(1)
select_list = Selenium::WebDriver::Support::Select.new(webDriver.find_element(xpath: '//select[@id=’cars’]'))
select_list.deselect_by(:index,'1')

Deselecting an item by value

Select lstStatus = new Select (webDriver.findElement(By.xpath("//select[@id=’cars’]")));
lstStatus.deselectByValue(‘Volvo’);
var lstStatus = webDriver.FindElement(By.XPath("//select[@id='status']"));
var selectElement = new SelectElement(lstStatus);
selectElement.DeselectByValue("Volo");
selectElement = Select(webDriver.find_element_by_id("//select[@id=’cars’]") )
selectElement.deselect_by_value("Volo")
select_list = Selenium::WebDriver::Support::Select.new(webDriver.find_element(xpath: '//select[@id=’cars’]'))
select_list.deselect_by(:value,'Volo')

Deselecting an item by visible text

Select lstStatus = new Select (webDriver.findElement(By.xpath("//select[@id=’cars’]")));
lstStatus.deselectByVisibleText(‘Volvo’);
var lstStatus = webDriver.FindElement(By.XPath("//select[@id='status']"));
var selectElement = new SelectElement(lstStatus);
selectElement.DeselectByText("Volo");
selectElement = Select(webDriver.find_element_by_id("//select[@id=’cars’]") )
selectElement.deselect_by_visible_text("Volo")
select_list = Selenium::WebDriver::Support::Select.new(webDriver.find_element(id: 'continents'))
select_list.deselect_by(:text,'Volo')

Deselecting all items

You can clear all selected items from a multi select element by calling .

NOTE: The deselect method will throw UnsupportedOperationException if the SELECT does not support multiple selections

Select lstStatus = new Select (webDriver.findElement(By.xpath("//select[@id=’cars’]")));
lstStatus.deselectAll();
var lstStatus = webDriver.FindElement(By.XPath("//select[@id='status']"));
var selectElement = new SelectElement(lstStatus);
selectElement.DeselectAll();
selectElement = Select(webDriver.find_element_by_id("//select[@id='status']") )
selectElement.deselect_all()
select_list = Selenium::WebDriver::Support::Select.new(webDriver.find_element(xpath: '//select[@id=’cars’]'))
select_list.deselect_all

Submitting a form

If given element is a form, or an element within a form, then the form will be submitted to the remote server. If this causes the current page to change, then this method will block until the new page is loaded.

webDriver.findElement(By.id("submitForm")).submit();
webDriver.FindElement(By.Id("submitForm")).Submit();
webDriver.find_element_by_id("btnSubmit").submit()
webDriver.find_element(:id, 'btnregister').submit

Locating an element

You have to locate element(s) before interacting with them. Various location strategies are available in Selenium. They are ID, Name, XPath, CSS, Classname ,tagname LinkText and partialLinkText.

If you want to locate the first element with a given strategy findElement  method can be used. findElement method is available for both WebDriver and WebElement.

Following will select the first element in the current page with name=’txtUsername’

webDriver.findElement(By.name("txtUsername")).sendKeys("Admin");
webDriver.FindElement(By.Name("txtUsername")).SendKeys("Admin");
webDriver.find_element_by_name("txtusername").send_keys("Admin")
webDriver.find_element(:name, 'txtusername').send_keys 'Admin'

 

Working with frames

You have to switch to a specific frame before working with the element in the frame. You will have to switch to the parent frame if you would like to work with a top level frame.

 

Switch to a frame by name or ID

webDriver.switchTo().frame("packageListFrame");
webDriver.SwitchTo().Frame("packageListFrame");
webDriver.switch_to.frame(“packageListFrame”)
webDriver.switch_to.frame webDriver.find_element(id: 'packageListFrame')

Switch to a frame by index

It is possible to switch to a frame by index. Index is zero based.

WebElement lnkElemnet = webDriver.findElement(By.linkText("com.thoughtworks.selenium"));        
webDriver.switchTo().frame(lnkElemnet);
webDriver.SwitchTo().Frame(webDriver.FindElement(By.LinkText("com.thoughtworks.selenium")));
webDriver.switch_to.frame(webDriver.find_element_by_link_text("com.thoughtworks.selenium"))
webDriver.switch_to.default_content

Switch to a frame by element

You can switch to a frame with previously located WebElement.

WebElement lnkElemnet = webDriver.findElement(By.linkText("com.thoughtworks.selenium"));        
webDriver.switchTo().frame(lnkElemnet);
webDriver.SwitchTo().Frame(webDriver.FindElement(By.LinkText("com.thoughtworks.selenium")));
webDriver.switch_to.frame(webDriver.find_element_by_link_text("com.thoughtworks.selenium"))
webDriver.switch_to.default_content

Switching to the parent window

You will have to switch to the parent frame before switching to a new frame if you have already switched to a frame.

webDriver.switchTo().frame(0);
webDriver.findElement(By.linkText("com.thoughtworks.selenium")).click();

webDriver.switchTo().parentFrame();
webDriver.switchTo().frame("classFrame");
webDriver.findElement(By.linkText("com.thoughtworks.selenium")).click();
 
webDriver.SwitchTo().Window(parentFrame);
webDriver.SwitchTo().Frame("classFrame");
webDriver.switch_to_default_content()
webDriver.switch_to.default_content

 

Working with Alerts

When a Javascript user prompt (or commonly known as alerts) window is present in the window it should be consumed (closed) before proceeding with next Selenium command. When a popup (Alert, confirmation or prompt)  window is present you will have to switch to the popup before working with them.

Switching to a popup window

Alert popupWindow= webDriver.switchTo().alert();
var popupWindow = webDriver.SwitchTo().Alert();
popupWindow = webDriver.switch_to_alert()
popupWindow = webDriver.switch_to.alert

Clicking OK button

OK button is present in all the popup windows. You can simulate clicking OK button by using the accept method.

popupWindow.accept();
popupWindow.Accept();
popupWindow.accept()
popupWindow.accept

Clicking Cancel button

Cancel button is present in all the confirmation and prompt popups. You can simulate clicking Cancel button by using the dismiss method.

popupWindow.dismiss();
popupWindow.Dismiss();
popupWindow.dismiss()
popupWindow.dismiss

Type string into an input box

A prompt box is often used if you want the user to input a value before entering a page. It is possible to simulate typing text into the input box using sendKeys method.

popupWindow.sendKeys(“Hello World”);
popupWindow.SendKeys("Hello World");
popupWindow.send_keys("Hello World")
popupWindow.send_keys 'Hello'

Get the message

All the popup windows have a message. You can get the message as a String.

popupWindow.getText();
popupWindow.Text;
popupWindow.text()
popupWindow.text

 

 accept()dismiss()getText()sendKeys()
Alert
Confirmation
Prompt

 

Window

Maximizing a browser window

Maximizes the current window if it is not already maximized.

webDriver.manage().window().maximize();
webDriver.Manage().Window.Maximize();
webDriver.maximize_window()
webDriver.manage.window.maximize

Minimizing a browser window

Selenium does not provide a method to minimize the browser windows. Hence minimizing browser windows could be achieved through indirect methods. Here are few workarounds.

  • Simulating user typing the shortcut keys for minimizing the window
  • Moving the browser window outside the screen’s display area
  • Clicking the minimize button in the right top corner  

 

Full screen

Full screen the current window if it is not already full screen.

webDriver.manage().window().fullscreen();
webDriver.FindElement(By.TagName("html")).SendKeys(Keys.F11);
webDriver.fullscreen_window()
webDriver.manage.window.full_screen

Move the browser window

We can use setPosition method to move the browser window. The positions (X and Y)  are given with respect to the upper left corner of the screen.

webDriver.manage().window().setPosition(new Point(50,200));
webDriver.Manage().Window.Position = new System.Drawing.Point(50, 200);
webDriver.set_window_position(200, 200)
webDriver.manage.window.resize_to(500, 500)

Resize browser window

We can use window().setSize() method to set the size of current  window.

We can set window width to 300 and height to 500 dimensions using bellow given syntax In selenium webdriver.

webDriver.manage().window().setSize(new Dimension(300,500));
webDriver.Manage().Window.Size = new Size(480, 320);
webDriver.set_window_size(300, 500)
webDriver.manage.window.resize_to(500, 500)

Taking  Screenshot of a webpage

File scrFile = ((TakesScreenshot) webDriver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(scrFile, new File("screenshot.png"));
((ITakesScreenshot)webDriver).GetScreenshot().SaveAsFile("test.png");
webDriver.save_screenshot('screen.png')
webDriver.save_screenshot("screenshot.png")

Taking screenshot of an element

There is not direct way to take screenshot of an element. You will have to crop the screenshot of a page to extract the specific area with the webelement. This will be discussed later in a separate blog post.

 

Timeouts in Selenium

Page load timeout

Page load timeout sets the amount of time to wait for a page load to complete before throwing an error. If the timeout is negative, page loads can be indefinite.

webDriver.manage().timeouts().pageLoadTimeout(60, TimeUnit.SECONDS);
webDriver.Manage().Timeouts().PageLoad = TimeSpan.FromSeconds(60);
webDriver.set_page_load_timeout(60)
webDriver.manage.timeouts.page_load = 60

Implicit wait

Specifies the amount of time the driver should wait when searching for an element if it is not immediately present.

webDriver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
webDriver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(30);
webDriver.implicitly_wait(10)
webDriver.manage.timeouts.implicit_wait = 60

Explicit wait

This is a conditional wait applied to a specific element before working with the element. There are various conditions available with Selenium WebDriver.

WebDriverWait wait = new WebDriverWait(webDriver, 10);
WebElement element = wait.until(ExpectedConditions.elementToBeClickable(By.id("logout")));
WebDriverWait wait = new WebDriverWait(webDriver, TimeSpan.FromSeconds(10));
wait.Until(ExpectedConditions.ElementToBeClickable(By.Id("logout")));
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

try:
    element = WebDriverWait(webDriver, 10).until(
        EC.presence_of_element_located((By.ID, "logout"))
    )
finally:
    webDriver.quit()
wait = Selenium::WebDriver::Wait.new(timeout: 10)
wait.until { webDriver.find_element(id: 'logout') }

Fluent wait

Fluent wait has ability to define the polling interval and exceptions to be ignored while waiting for specific condition. You can define the timeout value for specific condition as in explicit wait.

Wait wait = new FluentWait(webDriver)
       .withTimeout(30, SECONDS)
       .pollingEvery(5, SECONDS)
       .ignoring(NoSuchElementException.class);
DefaultWait wait = new DefaultWait(webDriver);
wait.Timeout = TimeSpan.FromSeconds(1);
wait.PollingInterval = TimeSpan.FromMilliseconds(100);
wait.IgnoreExceptionTypes(typeof(NoSuchElementException));
IWebElement element = wait.Until((d) =>{return d.FindElement(By.Id("textarea"));});
wait = WebDriverWait(webDriver, 10, poll_frequency=1, ignored_exceptions=[ElementNotVisibleException, ElementNotSelectableException])
element = wait.until(EC.element_to_be_clickable((By.ID, "textarea")))
wait = Selenium::WebDriver::Wait.new(timeout: 10)
wait.until { webDriver.find_element(id: 'logout') }

Please refer to our blog post on timeouts for more details.

 

Mouse operations

Actions class can be used for emulating the mouse operations. Action class is recommended over using Mouse directly.

Mouse hover

moveToElement method can be used to move the mouse to a specific web element. The element will be scrolled into the view.  If the offset is not defined as a parameter the mouse pointer is moved to middle of the element.

WebElement lnkJob= webDriver.findElement(By.xpath("//a/i[contains(text(),'Job')]"));        
Actions action= new Actions(webDriver);
action.moveToElement(lnkJob).build().perform();
Actions action = new Actions(webDriver);  
action.MoveToElement(webDriver.FindElement(By.XPath("//a/i[contains(text(),'Job')]"))).Perform();
hover = ActionChains(webDriver).move_to_element("//a/i[contains(text(),'Job')]")
hover.perform()
driver.action.move_to(:id, 'btnregister').perform

Drag and drop

It is easy to perform the drag and drop of an element to a specific element or to a given offset using .dragAndDrop and dragAndDropBy methods respectively.

Actions action = new Actions(webDriver);
action.dragAndDrop(sourceWebElement, targetWebElement).build().perform();
action.dragAndDrop(sourceWebElement,horizontalMoveOffset, verticalMoveOffset).build().perform();
Actions action  = new Actions(webDriver);
action .dragAndDrop(source element, target element);
action .build().perform();

            
action .dragAndDropBy(source element, xOffset, yOffset);
action .build().perform();
from selenium.webdriver.common.action_chains import ActionChains

source_element = webDriver.find_element_by_name('your element to drag')
dest_element = webDriver.find_element_by_name('element to drag to')
ActionChains(webDriver).drag_and_drop(source_element, dest_element).perform()
from = driver.find_element(:id, "draggable")
to = driver.find_element(:id, "droppable")
  
webDriver.action.click_and_hold(from).perform
webDriver.action.move_to(to).perform
webDriver.action.release.perform

Mouse click

Click method can be used for emulating user clicking the mouse on middle of a given web element or current location.

Actions action = new Actions(webDriver);
action.click(webElement).build().perform();
Actions action  = new Actions(webDriver);
action.MoveToElement(element).Perform();
menu = driver.find_element_by_css_selector(".nav")
hidden_submenu = driver.find_element_by_css_selector(".nav #submenu1")

actions = ActionChains(driver)
actions.move_to_element(menu)
actions.click(hidden_submenu)
actions.perform()
driver.action.move_to(element).click.perform

Double click

Mouse double click on the middle of a specific element or on current mouse location can be emulated.

Actions action= new Actions(webDriver);
action.doubleClick(webElement).build().perform();// Double click on webElement
action.doubleClick().build().perform();  //Double click on current mouse point 
Actions action = new Actions(webDriver);
action.DoubleClick(webElement).Build().Perform();// Double click on webElement
action.DoubleClick().Build().Perform(); //Double click on current mouse point
variable =  webDriver.find_element_by_id('nav-link-shopall')
actions = ActionChains(driver)
actions.move_to_element(variable)
actions.double_click(variable)
actions.perform()
webDriver.action.double_click(driver.find_element(:id, "Element ID")).perform

Click and hold mouse

clickAndHold method can be used for emulating user clicking the mouse and holding it until release method is called.

action.clickAndHold(webElement).build().perform();
action.clickAndHold().build().perform();
Actions action = new Actions(webDriver);
action.ClickAndHold(webElement).Build().Perform();
action.ClickAndHold().Build().Perform();
Actions action= new Actions(webDriver);
action.clickAndHold(WebElement).build().perform();
driver.action.move_to(element).click_and_hold(element).perform

Releasing the mouse button

It is possible to emulate releasing the depressed left mouse button at the middle of a given web element or at current mouse location.

action.release(targetWebElement).build().perform();
action.clickAndHold().build().perform();
Actions action = new Actions(webDriver);
action.Release(webElement).Build().Perform();
action.clickAndHold().Build().Perform();
actions = ActionChains(webDriver)
actions.click_and_hold(element)
actions.release(element)
actions.perform()
from = webDriver.find_element(:id, "draggable")
to = webDriver.find_element(:id, "droppable")

webDriver.action.click_and_hold(from).perform
webDriver.action.move_to(to).perform
webDriver.action.release.perform

 

References

Seleniumhq.org. (2018). Selenium WebDriver — Selenium Documentation. [online]
Available at: https://www.seleniumhq.org/docs/03_webdriver.jsp#introducing-the-selenium-webdriver-api-by-example
[Accessed 8 Jun. 2018].

Singh, V. (2018). TOOLSQA | Free QA Automation Tools Tutorials. [online] Toolsqa.com.
Available at: http://toolsqa.com/selenium-webdriver/handling-of-alerts-javascript-alerts-and-popup-boxes/
[Accessed 8 Jun. 2018].

WebDriver, H. (2018). How To Set/Get Window Position And Size In Selenium WebDriver. [online] Software-testing-tutorials-automation.com.
Available at: http://www.software-testing-tutorials-automation.com/2015/02/how-to-setget-window-position-and-size.html
[Accessed 8 Jun. 2018].

W3.org. (2018). WebDriver. [online]
Available at: https://www.w3.org/TR/webdriver1/#keyboard-actions
[Accessed 13 Jun. 2018].

Author: Janesh Kodikara

Performance Tester | JMeter Trainer | Software Testing Service Provider

Your Turn To Talk

Leave a reply:

Your email address will not be published.