One of the most fundamental and crucial interactions while Selenium automation testing is done by automating click operations over elements on a web page. We facilitate the click interaction using a method called Selenium.click().
Selenium click button method, although, is one of the most basic drills, it is often used inefficiently. Even experienced tester seems to miss out on the entire implementation of the click method is Selenium. They become occupied with writing complex test scenarios and forget that sometimes, a random click in the UI of a web application, can lead to a bug.
This is why, today, I will be talking about different ways in which you can make use of Selenium.click() command to help you perform automation testing with Selenium in a faster and better manner.
In this article, I will cover Selenium.click() in great detail. We will automate from basic to advanced interactions through the click.
If you are an experienced automation tester, you can skip the basic operations and head out to the advanced mouse operations. For beginners, we will start with a basic introduction of Selenium testing. Without further ado, let’s go!
Selenium is one of the most popular automation testing frameworks. Being a free, and open-source framework has made it a popular choice among the global tester community for automating the web testing experience. Selenium automation testing offers support for multiple programming languages and browsers like Google Chrome, Mozilla Firefox, Safari, Microsoft Edge, Internet Explorer, etc. making it a perfect choice to perform automated cross browser testing. Its popularity as an open-source has helped it to deliver compatibility across numerous test automation frameworks too! Let us have a quick and basic run down.
Selenium has 4 variants:
Selenium Webdriver also supports a headless browser like PhantomJS. Meanwhile, Selenium WebDriver has some disadvantages too like WebDriver cannot automate captcha. Using Selenium WebDriver for gaming and audio & video testing is not possible. The biggest flaw for Selenium WebDriver lies with its manner of test execution. Selenium WebDriver allows serial execution of test cases which makes it a little troubling for complex and large web-applications or test suite as it can take quite a while to validate sufficient test coverage.
As a solution, the Selenium Grid was introduced to allow testers to perform parallel testing with Selenium. Today, where automation testing is on the rise, Selenium plays a crucial role in helping startups & large enterprises into-market launch.
For a more detailed difference between these 4 Selenium variants, refer to our Selenium WebDriver tutorial.
Selenium offers a ‘.click()’ method to help you perform various mouse-based operations for your web-application. You can use the Selenium click button method for various purposes such as selecting the radio button and checkbox or simply clicking on any button or link, drag and drop, click and hold, etc.
In the next section, I am going to demonstrate the practical implementation of Selenium click button method in for basic operations, and advanced operations. After that, I will also show you how you can use CSS selectors with the Selenium .click method.
Let’s start with the basic operations that your perform using the Selenium click button method for automation testing. We will do so with the help of Action class. Action class is an ability used to handle any mouse operation with the Selenium click button method. It comes as an in-built ability for Selenium automation testing. You can also leverage action class for keyboard interactions.
The most basic operation using a Selenium click button method is a left-click or a mouse click.
Test Scenario: Visit LambdaTest Homepage and click on the Login button.
Example code for the test scenario:
driver.get("https://www.lambdatest.com/");
driver.findElement(By.linkText("Login")).click(); //using Selenium click button method
You can also use the Selenium .click() button for enabling/disabling checkboxes, radio buttons.
Test Scenario 2: After you click on the LambdaTest Login button, tick the checkbox for “Remember me”.
WebElement chkBx = driver.findElement(By.className("mycheckbox"));
boolean flag2 = chkBx.isSelected();
System.out.println(flag2);
if(flag2) //true
{
System.out.println("checkbox is already selected");
}
else //false
{
System.out.println("select checkbox");
chkBx.click();
Note: To confirm whether a checkbox or a radio button is selected or not, we make us of the isSelected().
In some of the scenarios while Selenium automation testing of a web page, you may need to automate right click over a button, text, image or more.
Test Scenario: Go to LambdaTest Live and open the video in a new tab.
Action class may be ineffective to automate this scenario as we are trying to open a right-click menu of the Google Chrome browser. Action class has few restrictions around the keyboard usage, you can only declare modifier keys such as Shift, Ctrl, CapsLk, etc. using the actions class. However, you can use the Robot class to leverage keyboard inputs that are different from modifier keys.
We will be using the Robot class here to capture the elements of the right-click menu and perform a click on one of those elements to automate using the Selenium click button method.
package postBlo;
import java.awt.AWTException;
import java.awt.Robot;
import java.awt.event.KeyEvent;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;
public class Lambda {
public static void main(String[] args) throws InterruptedException, AWTException {
System.setProperty("webdriver.chrome.driver", "./exefiles/chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("https://www.lambdatest.com/feature");
Actions actions = new Actions(driver);
WebElement elementLocator = driver.findElement(By.xpath("//*[@id=\"vid\"]"));
actions.contextClick(elementLocator).sendKeys(Keys.ARROW_DOWN).sendKeys(Keys.ARROW_DOWN).sendKeys(Keys.ARROW_DOWN).build().perform();
Actions action = new Actions(driver);
action.contextClick(elementLocator).build().perform();
Robot robot = new Robot();
Thread.sleep(2000);
robot.keyPress(KeyEvent.VK_DOWN);
Thread.sleep(2000);
robot.keyPress(KeyEvent.VK_DOWN);
Thread.sleep(2000);
robot.keyPress(KeyEvent.VK_DOWN);
Thread.sleep(2000);
robot.keyPress(KeyEvent.VK_ENTER);
}
}
Mouse hover is a vital part of any cross browser testing checklist. Many times you want to check whether the styling applied over a web element is supported in a consistent manner when accessed from different browsers or not? You can also use a mouse hover to verify a prompt message over a button.
Test Scenario: Visit LambdaTest Pricing and perform a mouse hover on the text “What are parallel tests?”. After understanding what parallel tests are picking a parallel test value from the drop-down.
In a few projects, some time elements are not visible or element is disabled in this case we need to take the help of JavaScript Executor. While working on not visible elements gives an “illegalStateException” and we can get rid of this using the JavascriptExecutor.
JavascriptExecutor js = (JavascriptExecutor) driver;
WebElement el = driver.findElement(By.id("id"));
js.executeScript("arguments[0].scrollIntoView();", el);
Example Script for Test Scenario:
package postBlo;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;
public class MouseHover {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "./exefiles/chromedriver.exe");
// ChromeDriver c = new ChromeDriver();
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("https://www.lambdatest.com/pricing");
((JavascriptExecutor) driver).executeScript("scroll(0,300)");
Actions ac = new Actions(driver);
WebElement wb = driver.findElement(By.xpath("/html/body/div[2]/section[1]/div/div[2]/div[2]/div[1]/div/div/div[3]/p"));
ac.moveToElement(wb).build().perform();
Thread.sleep(3000);
WebElement plan = driver.findElement(By.xpath("/html/body/div[2]/section[1]/div/div[2]/div[2]/div[2]/div/div/div[2]/div/div/button"));
plan.click();
Thread.sleep(2000);
driver.findElement(By.xpath("//a[text()='4 Parallel Tests(25 Users)']")).click();
Thread.sleep(4000);
driver.quit();
}
}
With basic operations covered, we now step into performing advanced operations using the Selenium click button method.
We can use movebyOffset to perform a click anywhere on the page by feeding (x,y) coordinates to the WebDriver. You can even generate a click on blank portions of your webpage as long as you are aware of the (X,Y) coordinates.
Test Scenario: Visit LambdaTest Homepage and find the (x,y) coordinates for the button “Start Free Testing”.
In the above image, you can notice the X, Y coordinates specified under the highlighted “Start Free Testing” button.
driver.get("https://www.lambdatest.com");
Actions act = new Actions(driver);
act.moveByOffset(913, 477).contextClick().build().perform();
Note: These (X, Y) coordinates will be different from one screen resolution and screen size to another.
Double click is an absolute must for Selenium automation testing be it for performance or automated browser testing. Here is an example of how you can perform double click using Selenium automation scripts.
driver.get("https://www.lambdatest.com");
Actions act = new Actions(driver);
//Double click on element
WebElement wb2 = driver.findElement(By.xpath("/html/body/div[2]/section[1]/div/div/h1"));
act.doubleClick(wb2).perform();
Many times when you are performing automation testing with Selenium, you may come across a requirement where you would need to highlight a text, image by clicking and holding the mouse. Let us take a scenario to automate this interaction.
Test Scenario: Visit JQuery UI Draggable Interface, perform a click and hold over the draggable box and then move using the offset.
Here is the code to automate click and hold, along with movebyoffset.
driver.get("https://jqueryui.com/draggable/");
driver.manage().window().maximize();
Actions action = new Actions(driver);
driver.switchTo().frame(0);
WebElement ele = driver.findElement(By.id("draggable"));
action.moveToElement(ele).clickAndHold().moveByOffset(310, 220).build().perform();
Thread.sleep(4000);
driver.quit();
Somewhat similar but slightly different than Click and Hold, is the requirement for Drag and Drop. Here, the place to drop after dragging is specifically prominent in the UI so you know where to place an element.
Test Scenario: Visit JQuery UI Droppable Interface, perform a click on the draggable box, and then drop it in the container box.
Here is how you can automate the above-mentioned test scenario using the Selenium click button method.
driver.get("https://jqueryui.com/droppable/");
driver.manage().window().maximize();
Actions action = new Actions(driver);
driver.switchTo().frame(0);
WebElement drag = driver.findElement(By.id("draggable"));
WebElement drop = driver.findElement(By.id("droppable"));
action.dragAndDrop(drag, drop).build().perform();
Thread.sleep(4000);
driver.quit();
Locators in Selenium allow you to locate a web element over a web page. There are 8 types of locators(identifire) in Selenium. Let’s see how you can perform a click in Selenium using different Locators.
Wherever an ID is specified in the HTML code for any web element, you can leverage that in your Selenium automation testing scripts to locate that particular web element. The ID of a web element would always be unique which makes it a very powerful way to locate web elements automatically using Selenium automation testing. To automate clicks using an ID locator you would need to specify in your code as below.
driver.findelement (by.id(“idLocator”)).click();
Similarly, you can find the name of a web element by inspecting the HTML and use it to locate the web element using Selenium automation testing. To use the Selenium click button with Name locator, you need to address it in a similar way.
driver.findelement (by.name(“password”).sendkeys(“123456789”);
I rarely use the Class name as an alternative to other locators in Selenium. Inspect a web element, find its class name, and locate it using your Selenium automation scripts.
driver.findelement (by.class.name(“mycheckbox”)).click();
Whenever there is a webelement with unique HTML tag we can use the TagName locator in Selenium automation testing. There can be many types of Unique HTML tag such as:
Hyperlink – < a >
Image – < img >
Header – < h1 >
So for example, if you have a unique Hyperlink TagName using the anchor tag then you can incorporate Selenium click button interaction using the below code.
driver.findelement(by.tagname(“a”)).click();
If there is a hyperlink with a unique HTML tag then we can make use of the LinkText locator. Here we specify the text over which a Hyperlink is triggered on a webpage through a click.
driver.findelement(by.linktext(“facebook”).click();
You can specify the text for a hyperlink even partially and locate it using the Partial Link Text locator. For example, if we wish to locate a web element with a hyperlink that says Amazon then we can do so using the below command.
driver.findelement(by.partiallinktext(“zon”)).click();
A more cross browser compatible locator than Xpath is a CSS selector as a primary browser such as Google Chrome and Mozilla Firefox are designed to optimize the execution time for a CSS selector.
driver.findElement(By.cssSelector("#app > section > form > div > div > input:nth-child(3)")).click();
Note: Whenever we use CSS selector or Xpath as a locator we should not use mandatory attribute because mandatory attribute will be the same for similar kind of webelement so it is always recommended to go for additional attributes.
XPath is a locator that is used to locate the webelement based on the tag, attribute, text, etc. we can use Xpath for HTML as well as for XML Docs.
driver.findElement(By.xpath("//*[@id=\"app\"]/section/form/div/div/input[1]")).click();
Here is a cool tip using which you can click on every hyperlink on a webpage. Gotta click em all!
Test Scenario: Visit LambdaTest Homepage and click on every hyperlink invoked through the anchor tag in HTML.
Below is a script which is generating a list of hyperlinks on the LambdaTest Homepage where the tagName is “a” which represents an anchor tag. After that, it would click on every link a single time, in random order. The script would visit the first link, go to the respective web page and then will roll back to LambdaTest to visit the next link and the cycle will go on till every link is visited a single time.
package pack1;
import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class ClickRandom {
public static void main(String[] args) throws InterruptedException {
System.setProperty("webdriver.chrome.driver", "./exefiles/chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get("https://www.lambdatest.com/");
List<WebElement> link = driver.findElements(By.tagName("a"));
int linkcount = link.size();
System.out.println(linkcount);
for (int i = 0; i < linkcount; i++) {
String linktext = link.get(i).getText();
System.out.println(linktext);
}
Random r = new Random();
link.get(r.nextInt(2)).click();
String title = driver.getTitle();
System.out.println("Page Title is " + title);
Thread.sleep(5000);
driver.get("https://www.lambdatest.com/");
}
}
Console Output:
As you can see there were in total 47 hyperlinks that were accumulated by the test automation scripts. They are visited one by one! I will leave it for you to find a way of incorporating this in your automated browser testing scripts.
Sometimes to reproduce a bug on a UI element, you may need to automate a loop to witness whether a bug was encountered in X number of trials. I am going to show you how to create a Java loop for the Selenium click button.
Test Scenario: Login to the LambdaTest application. Go to the profile icon on top-right and click to open the menu, then click to close it. Continue the drill for 75 clicks to see if any anomaly is encountered.
package postBlo;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class ClickMultipleOnLink {
public static void main(String[] args) throws Exception {
System.setProperty("webdriver.chrome.driver", "./exefiles/chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("https://accounts.lambdatest.com/login");
driver.findElement(By.name("email")).sendKeys("[email protected]");
driver.findElement(By.name("password")).sendKeys("1234567");
driver.findElement(By.xpath("/html/body/div[1]/section/form/div/div/button\r\n" +
"")).click();
Thread.sleep(2000);
driver.findElement(By.xpath("/html/body/div[2]/header/aside/ul/li[2]/a")).click();
Thread.sleep(2000);
for (int i = 0; i < 75; i++) {
driver.findElement(By.id("navbarDropdown")).click();
Thread.sleep(1000);
}
}
}
By far, I hope you have a good understanding of how powerful the Selenium .click() button method can be and how you can leverage it. I hope the bonus tips were helpful for your daily automated browser testing scripts. Do you want to share a bonus tip too or a unique way in which you used the Selenium click button method? If so, drop your thoughts in the comment section below!
Previously published at https://www.lambdatest.com/blog/selenium-click-button-with-examples/