[Selenium+Java] https://www.guru99.com/using-robot-api-selenium.html

   2023-03-08 学习力0
核心提示:p.p1 { margin: 0; font: 14px "PingFang SC"; color: rgba(0, 0, 0, 1); -webkit-text-stroke: #000000; background-color: rgba(255, 255, 255, 1) }span.s1 { font-kerning: none }Original URL: https://www.guru99.com/using-robot-api-selenium.html 

Original URL: https://www.guru99.com/using-robot-api-selenium.html

 

Why Robot Class?

In certain Selenium Automation Tests, there is a need to control keyboard or mouse to interact with OS windows like Download pop-up, Alerts, Print Pop-ups, etc. or native Operation System applications like Notepad, Skype, Calculator, etc.

Selenium Webdriver cannot handle these OS pop-ups/applications.

In Java version 1.3 Robot Class was introduced. Robot Class can handle OS pop-ups/applications.

In this tutorial, you will learn,

Benefits of Robot Class

  1. Robot Class can simulate Keyboard and Mouse Event
  2. Robot Class can help in upload/download of files when using selenium web driver
  3. Robot Class can easily be integrated with current automation framework (keyword, data-driven or hybrid)

Documentation of Robot Class

Robot Class documentation will help you to understand the basic definition, syntax and usage of all methods, and functions available in Robot Class . You can view the documentation on Official Oracle website, or you can create the documentation on your local machine.

To create the documentation on local machine, follow the steps below-

Step 1) You will find the src.zip file in JDK folder. Copy src.zip and extract the same in some other folder or directory (say D: or E: )

[Selenium+Java] https://www.guru99.com/using-robot-api-selenium.html

Step 2) Extract src folder and Navigate to (path till src folder)/src/java/awt

Step 3) Copy the current location of awt folder and open command prompt.

Step 4) In cmd, change your current directory location to awt folder and type 'javadoc *.java' as shown below

[Selenium+Java] https://www.guru99.com/using-robot-api-selenium.html

Wait a while for the system to process, once completed you will see few HTML files in awt folder.

Step 5) Open index.html

[Selenium+Java] https://www.guru99.com/using-robot-api-selenium.html

Step 6) Here's you have full documentation of awt package, from the left navigation bar click on 'Robot' hyperlink (See 1 marked in below image).

[Selenium+Java] https://www.guru99.com/using-robot-api-selenium.html

Here you can also see all the methods and interfaces of Robot Class (See 2 marked in above image).

Understanding Robot Class internal methods and usage

Robot Class methods can be used to interact with keyboard/mouse events while doing browser automation. Alternatively AutoIT can be used, but its drawback is that it generates an executable file (exe) which will only work on windows, so it is not a good option to use.

Some commonly and popular used methods of Robot Class during web automation:

  • keyPress(): Example: robot.keyPress(KeyEvent.VK_DOWN) : This method with press down arrow key of Keyboard
  • mousePress() : Example : robot.mousePress(InputEvent.BUTTON3_DOWN_MASK) : This method will press the right click of your mouse.
  • mouseMove() : Example: robot.mouseMove(point.getX(), point.getY()) : This will move mouse pointer to the specified X and Y coordinates.
  • keyRelease() : Example: robot.keyRelease(KeyEvent.VK_DOWN) : This method with release down arrow key of Keyboard
  • mouseRelease() : Example: robot.mouseRelease(InputEvent.BUTTON3_DOWN_MASK) : This method will release the right click of your mouse

Sample code to automate common use cases using Robot Class

  • Lets take example of web site http://spreadsheetpage.com/index.php/file/C35/P10/ wherein after you click on a web element (.//a[@href=contains(text(),'yearly-calendar.xls']) a O.S download pop-up appears.
  • To handle this we use Robot class (by creating an instance of Robot Class in your code say Robot robot = new Robot()) . Robot class us present in AWT package of JDK.
  • To press down arrow key of Keyboard we use (robot.keyPress(KeyEvent.VK_DOWN))
  • To press TAB key of keyboard (we use robot.keyPress(KeyEvent.VK_TAB))
  • To press Enter key we use (robot.keyPress(KeyEvent.VK_ENTER)).

Here is a sample code

import java.awt.AWTException;	
import java.awt.Robot;	
import java.awt.event.KeyEvent;	
import org.openqa.selenium.By;	
import org.openqa.selenium.WebDriver;	
import org.openqa.selenium.firefox.FirefoxDriver;	

class Excercise1 {	

      public static void main(String[] args) throws AWTException, InterruptedException {	
           WebDriver driver = new FirefoxDriver();	
           driver.get("http://spreadsheetpage.com/index.php/file/C35/P10/"); // sample url	
           driver.findElement(By.xpath(".//a[@href=contains(text(),'yearly-calendar.xls')]")).click();	
           Robot robot = new Robot();  // Robot class throws AWT Exception	
           Thread.sleep(2000); // Thread.sleep throws InterruptedException	
           robot.keyPress(KeyEvent.VK_DOWN);  // press arrow down key of keyboard to navigate and select Save radio button	
           
           Thread.sleep(2000);  // sleep has only been used to showcase each event separately	
           robot.keyPress(KeyEvent.VK_TAB);	
           Thread.sleep(2000);	
           robot.keyPress(KeyEvent.VK_TAB);	
           Thread.sleep(2000);	
           robot.keyPress(KeyEvent.VK_TAB);	
           Thread.sleep(2000);	
           robot.keyPress(KeyEvent.VK_ENTER);	
       // press enter key of keyboard to perform above selected action	
     }	 
 }	

Check this video to see it in action

How to execute Robot Class code using TestNG

Since, now you aware of basic methods of Robot Class so let's understand few more complex methods -

Suppose you do not want to use the click method for clicking at web element.

In such cases, you can use mouseMove method of the Robot class.

Step 1) mouseMove method takes x and y coordinates as parameters like robot.mouseMove(630, 420) where 630 indicates x-axis and 420 indicate y-axis. So, this method will move your mouse pointer from the current location to mentioned x and y intersection point.

Step 2) Next, we need to press the mouse button. We can use the method mousePress like robot.mousePress(InputEvent.BUTTON1_DOWN_MASK) .

Step 3) After press, the mouse needs to be released. We can use robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK) in order to release left click of a mouse.

Running code using testNG:

Running code using Testng requires maven dependency of testNG or referenced library of TestNG jar file.

TestNG maven dependency:

<dependency>	
  <groupId>org.testng</groupId>
  <artifactId>testng</artifactId>	
  <version>6.1.1</version>	
</dependency>	

After adding maven dependency or jar file. You need to import Test annotation of testNG. Once it is all done, just Right click on the program code and click on Run As then click on TestNG… and you will find that code will start its execution using testNG API.

Here is the code

import java.awt.AWTException;	
import java.awt.Robot;	
import java.awt.event.InputEvent;	
import java.awt.event.KeyEvent;	
import org.openqa.selenium.WebDriver;	
import org.openqa.selenium.firefox.FirefoxDriver;	
import org.testng.annotations.Test;	

public class Excersise1 {	

    @Test	
    public static void  execution() throws InterruptedException, AWTException {
        WebDriver driver = new FirefoxDriver();	
        driver.manage().window().maximize();	
        driver.get("http://spreadsheetpage.com/index.php/file/C35/P10/"); // sample url	
        Robot robot = new Robot();	
        robot.mouseMove(630, 420); // move mouse point to specific location	
        robot.delay(1500);        // delay is to make code wait for mentioned milliseconds before executing next step	
        robot.mousePress(InputEvent.BUTTON1_DOWN_MASK); // press left click	
        robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK); // release left click	
        robot.delay(1500);	
        robot.keyPress(KeyEvent.VK_DOWN); // press keyboard arrow key to select Save radio button	
        Thread.sleep(2000);	
        robot.keyPress(KeyEvent.VK_ENTER);	
        // press enter key of keyboard to perform above selected action	
    }	
}	

Check this video to see it in action

Disadvantages of Robot Class

Robot framwork has few disadvantages mentioned below:

  1. Keyword/mouse event will only works on current instance of Window. E.g. suppose a code is performing any robot class event, and during the code execution user has moved to some other screen then keyword/mouse event will occur on that screen.
  2. Most of the methods like mouseMove is screen resolution dependent so there might be a chance that code working on one machine might not work on other.

Summary

Robot class in AWT package is used to generate keyboard/mouse events to interact with OS windows and native apps.

The primary purpose of Robot is to support selenium automated tests project build in Java platform

This article is contributed by Ramandeep Singh, who is a test automation engineer at a leading MNC.

 
反对 0举报 0 评论 0
 

免责声明:本文仅代表作者个人观点,与乐学笔记(本网)无关。其原创性以及文中陈述文字和内容未经本站证实,对本文以及其中全部或者部分内容、文字的真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
    本网站有部分内容均转载自其它媒体,转载目的在于传递更多信息,并不代表本网赞同其观点和对其真实性负责,若因作品内容、知识产权、版权和其他问题,请及时提供相关证明等材料并与我们留言联系,本网站将在规定时间内给予删除等相关处理.

  • HTML中将背景颜色渐变 html设置背景颜色渐变
    通过使用 css3 渐变可以让背景两个或多个指定的颜色之间显示平稳的过渡,由于用到css3所以需要考虑下浏览器兼容问题,例如:从左到右的线性渐变,且带有透明度的样式:#grad {background: -webkit-linear-gradient(left,rgba(255,0,0,0),rgba(255,0,0,1)); /*
    03-08
  • html5 Canvas 如何自适应屏幕大小
    但是这样创建出的画布不能随着浏览器窗口大小的改变而动态的改变画布的大小。而这一点往往又非常重要, 因为我们会经常改变浏览器窗口大小,不会一直保持某个固定的大小。 html代码 canvas width="300" height="300" id="myCanvas"/canvas设置样式 * {
    03-08
  • Vue中出现Do not use built-in or reserved HTML elements as component id:footer等等vue warn问题
    Vue中出现Do not use built-in or reserved HTM
    错误示图:原因:是因为在本地项目对应文件的script中,属性name出现了错误的命名方式,导致浏览器控制台报错!  诸如: name: header 、  、 name: menu , 等等都属于错误的命名方式等 错误代码命名如下:解决办法:办法1: 如果我们采用正确命名
    03-08
  • HTML在网页中插入音频视频简单的滚动效果
    HTML在网页中插入音频视频简单的滚动效果
    每次上网,打开网页后大家都会看到在网页的标签栏会有个属于他们官网的logo,现在学了HTML了,怎么不会制作这个小logo呢,其实很简单,也不需要死记硬背,每当这行代码出现的时候能知道这是什么意思就ok1 link rel="shortcuticon" type="image/x-icon" href="
    03-08
  • HTML的video标签,不能下载视频代码
    !-- 在线视频不能下载代码 --!DOCTYPE html html headscript src="../Demo/demo/book/JQuery/jQuery v2.2.0.js"/script/headbody div style="text-align:center;"video src="../images/PreviewVideo.mp4" width="820"controls="controls&
    03-08
  • ThinkPHP报错 The requested URL /admin/index/login.html was not found on this server.
    ThinkPHP报错 The requested URL /admin/index/
           解决方案在入口文件夹public下查看.htaccess是否存在。不存在则新建,存在的话,那内容替换为下面这串代码 就可以解决Not Fund#IfModule mod_rewrite.c#Options +FollowSymlinks -Multiviews#RewriteEngine On##RewriteCond %{REQUEST_FILENAME
    03-08
  • HTML特殊字符、列表、表格总结 html特殊符号对
            HTML实体字符  在HTML中一些特殊的字符需要用特殊的方式才能显示出来,比如小于号、版权等,  在课堂上老师教了我们一个有点意思的:空格,在教材上字符实体是“nbsp”通过老师  的演示我们发现不同的浏览器他所显示的效果不同,有的比
    03-08
  • 【JavaScript】使用document.write输出覆盖HTML
    您只能在 HTML 输出中使用 document.write。如果您在文档加载后使用该方法,会覆盖整个文档。分析HTML输出流是指当前数据形式是HTML格式的数据,这部分数据正在被导出、传输或显示,所以称为“流”。通俗的来说就是HTML文档的加载过程,如果遇到document.writ
    03-08
  • ASP.Net MVC 控制@Html.DisplayFor日期显示格式
    在做一個舊表的查詢頁時,遇到一個問題:字段在db里存儲的是DATETIME,但保存的值只有日期,沒有時間數據,比如2018/2/26 0:00:00,顯示出來比較難看,當然也可以做一個ViewModel,在字段上添加Attribute定義來更改名稱和顯示名稱,如下:[Display(Name = "建
    03-08
  • html 基础代码
    title淄博汉企/title/headbody bgcolor="#00CC66" topmargin="200" leftmargin="200" bottommargin="200"a name="top"/a今天br /天气nbsp;nbsp;nbsp;nbsp;nbsp;不错br /font color="#CC0000"格式控制标签br /b 文字加粗方式1\bbr /str
    03-08
点击排行