Selenium 简明教程
Selenium WebDriver - Action Class
Selenium Webdriver 可用于执行键盘和鼠标操作。这包括拖放、单击、双击、右键单击、配合控制键使用、其他按键操作等操作。所有这些操作都是使用指定的用户交换 API(在 Selenium Webdriver 中称为 Actions 类)执行的。
Selenium Webdriver can be used to perform keyboard and mouse operations. This includes actions like drag and drop, click, double click, right click, working with control keys, other key operations, and so on. All these actions are carried out with designated user exchange APIs, known as the Actions class in Selenium Webdriver.
Action Class Methods
Actions 类中提供的一些方法列在下面 −
Some of the methods available in the Actions class are listed below −
-
click() − This method is used to perform click at the present location of the mouse.
-
build() − This method is used to create a combination of actions having all the actions to be carried on.
-
perform() − This method is used to perform actions without invoking the build() first.
-
release() − This method is used to release mouse action at the present location of the mouse.
-
release(WebElement e) − This method is used to release mouse action at the middle of the webElement e passed as a parameter.
-
doubleClick(WebElement e) − This method is used to perform double click at the middle of the webElement e passed as a parameter.
-
click(WebElement e) − This method is used to perform click at the middle of the webElement e passed as a parameter.
-
doubleClick() − This method is used to perform double click at the present location of the mouse.
-
contextClick() − This method is used to perform a right click at the present location of the mouse.
-
contextClick(WebElement e) − This method is used to perform a right click at the middle of the webElement e passed as a parameter.
-
moveToElement(WebElement e) − This method is used to move the mouse to the middle of the webElement e passed as a parameter.
-
moveToElement(WebElement e, int x-offset, int y-offset) − This method is used to move the mouse to an offset from the element in view point. The webelement e, x, and y offset values are passed as parameters.
-
clickAndHold() − This method is used to perform click(without releasing) at the present location of the mouse.
-
clickAndHold(WebElement e) − This method is used to perform click(without releasing) at the middle of the webElement e passed as a parameter.
-
keyDown(CharSequence key) − This method is used to perform a modifier key press, passed as a parameter.
-
keyDown(WebElement e, CharSequence key) − This method is used to perform a modifier key press post focusing an element. The webElement e, and key to be pressed are passed as parameters.
-
keyUp(CharSequence key) − This method is used to perform a modifier key release, passed as a parameter.
-
keyUp(WebElement e, CharSequence key) − This method is used to perform a modifier key release post focusing an element. The webElement e, and key to be released are passed as parameters.
-
sendKeys(CharSequence key) − This method is used to send keys to elements in focus. The key to be sent is passed as a parameter.
-
sendKeys(WebElement e, CharSequence key) − This method is used to send keys to the webElement passed as parameter.
请注意,在使用 Actions 类的这些方法时,我们需要添加导入语句——
Please note that, while using the methods of Actions class, we would need to add the import statement −
import org.openqa.selenium.interactions.Actions in our tests.
Example 1 - Click, Right & Double Clicks
让我们看下面这个页面的示例,我们通过分别单击网页上的 Click Me, Right Click Me 和 Double Click Me 按钮,来执行单击、右键单击和双击。
Let us take an example of the below page, where we would perform click, right click, and double click by clicking on the Click Me, Right Click Me, and Double Click Me buttons respectively on the web page.
分别执行 Click Me, Right Click Me 和 Double Click Me 按钮后,我们将在页面上分别收到消息 You have a dynamic click 和 You have double clicked 。
On performing the Click Me, Right Click Me, and Double Click Me buttons respectively, we would get a message You have a dynamic click and You have double clicked messages on the page respectively.
代码实现
Code Implementation
package org.example;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;
import java.util.concurrent.TimeUnit;
public class ActionsMouse {
public static void main(String[] args) throws InterruptedException {
// Initiate the Webdriver
WebDriver driver = new ChromeDriver();
// adding implicit wait of 15 secs
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
// Opening the webpage
driver.get("https://www.tutorialspoint.com/selenium/practice/buttons.php");
// identify element with xpath for click
WebElement m = driver.findElement
(By.xpath("/html/body/main/div/div/div[2]/button[1]"));
// object of Actions class to move then click
Actions a = new Actions(driver);
a.moveToElement(m).click().build().perform();
// get text after click
WebElement t = driver.findElement(By.xpath("//*[@id='welcomeDiv']"));
System.out.println("Text after click: " + t.getText());
// identify element with xpath for double click
WebElement n = driver.findElement
(By.xpath("/html/body/main/div/div/div[2]/button[3]"));
// double click
a.moveToElement(n).doubleClick().build().perform();
// get text after double click
WebElement x = driver.findElement(By.xpath("//*[@id='doublec']"));
System.out.println("Text after double click: " + x.getText());
// identify element with xpath for right click
WebElement y = driver.findElement
(By.xpath("/html/body/main/div/div/div[2]/button[2]"));
// right click
a.moveToElement(y).contextClick().build().perform();
// Closing browser
driver.quit();
}
}
Output
Text after click: You have done a dynamic click
Text after double click: You have Double clicked
Process finished with exit code 0
在上面的示例中,我们执行了单击、双击和右键单击,然后在控制台中收到了消息 - Text after click: You have done a dynamic click 和 Text after double click: You have Double clicked 。
In the above example, we had performed click, double click, and right click and then received the messages in the console - Text after click: You have done a dynamic click and Text after double click: You have Double clicked.
最后,收到了消息 Process finished with exit code 0 ,表示代码成功执行。
Finally, the message Process finished with exit code 0 was received, signifying successful execution of the code.
Example 2 - Mouse Hover
让我们来看另一个示例,最初菜单 Navbar 是黑色的。
Let us take another example, where initially the menu Navbar has a black color.
但是,悬停并按住它后,菜单 Navbar 会从黑色变为绿色,如下图所示。
However, on hovering and holding on it, the menu Navbar changes color from black to green as shown in the below image.
代码实现
Code Implementation
package org.example;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;
import java.util.concurrent.TimeUnit;
public class ActionsClickandHold {
public static void main(String[] args) throws InterruptedException {
// Initiate the Webdriver
WebDriver driver = new ChromeDriver();
// adding implicit wait of 15 secs
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
// Opening the webpage
driver.get("https://www.tutorialspoint.com/selenium/practice/menu.php#");
// identify element with xpath for click and hold
WebElement m = driver.findElement
(By.xpath("/html/body/main/div/div/div[2]/nav/div/a"));
// get element color in rgba format
String s = m.getCssValue("color");
System.out.println("rgba code for color element: " + s );
// object of Actions class to click and hold
Actions a = new Actions(driver);
a.clickAndHold(m).build().perform();
// get element color in rgba format
String c = m.getCssValue("color");
System.out.println("rgba code for color for element after click and hold: " + c);
// Closing browser
driver.quit();
}
}
Example 3 - Drag and Drop
让我们看上面这个页面的示例,我们将把包含文本的源框 - Drag me to my target 拖到包含文本的目的地框 - Drop here 。
Let us take an example of the above page, where we would drag the source box with the text - Drag me to my target to the destination box having the text - Drop here.
一旦整个操作完成,我们将在网页上看到文本 - Dropped! ,如下面的图像所示。
Once the entire action has been completed, we would get the text - Dropped! on the web page as highlighted on the below image.
代码实现
Code Implementation
package org.example;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;
import java.util.concurrent.TimeUnit;
public class DragAndDrp {
public static void main(String[] args) throws InterruptedException {
// Initiate the Webdriver
WebDriver driver = new ChromeDriver();
// adding implicit wait of 15 secs
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
// URL launch for accessing drag and drop elements
driver.get("https://www.tutorialspoint.com/selenium/practice/droppable.php");
// identify source and target elements for drag and drop
WebElement sourceElement= driver.findElement(By.id("draggable"));
WebElement targetElement= driver.findElement(By.id("droppable"));
// drag and drop operations without build and perform methods
Actions a = new Actions(driver);
a.dragAndDrop(sourceElement, targetElement).build().perform();
// identify text after element is dropped
WebElement text = driver.findElement(By.xpath("//*[@id='droppable']/p"));
System.out.println("Text is : " + text.getText());
// quitting browser after drag and drop operations completed
driver.quit();
}
}
Output
Text is after dragging: Dropped!
Process finished with exit code 0
在上一个示例中,我们首次从源位置执行拖放操作到目标定位器,并且还在控制台中接收到了如下消息—— Text is : Dropped! (在完成此应用程序中的拖放操作后接收)
In the above example, we had first performed a drag and drop operation from the source to the destination locator, and also received the message in the console - Text is : Dropped!(which is received after drag and drop operation has been completed in this application).
最后,收到了消息 Process finished with exit code 0 ,表示代码成功执行。
Finally, the message Process finished with exit code 0 was received, signifying successful execution of the code.
Example 4 - Key Operation
让我们看另一个示例,我们在输入框中使用操作类中的按键抬起/按键按下方法来输入大写字母 SELENIUM 。请注意,在将值发送到 sendKeys() 方法时,我们会在按下 SHIFT 键的同时传递 selenium 。因此,我们在输入框中输入的输出为 SELENIUM 。
Let us take another example, where we would enter text SELENIUM in an input box in capital letters using the Key Up Key Down methods of Action class. Please note that, while sending the value to the sendKeys() method, we would pass selenium along with pressing SHIFT keys. Hence, we would get the output entered in the input box as SELENIUM.
package org.example;
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;
import java.util.concurrent.TimeUnit;
public class KeyAction {
public static void main(String[] args) throws InterruptedException {
// Initiate the Webdriver
WebDriver driver = new ChromeDriver();
// adding implicit wait of 15 secs
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
// Opening the webpage where we will identify an element
driver.get("https://www.tutorialspoint.com/selenium/practice/text-box.php");
// Identify the first input box with xpath locator
WebElement e = driver.findElement(By.xpath("//*[@id='fullname']"));
// Actions class
Actions a = new Actions(driver);
// moving to an input box and clicking on it
a.moveToElement(e).click();
// key UP and DOWN action for SHIFT
a.keyDown(Keys.SHIFT);
a.sendKeys("Selenium").keyUp(Keys.SHIFT).build().perform();
// get value entered
System.out.println("Text entered: " + e.getAttribute("value"));
// Closing browser
driver.quit();
}
}
Output
Text entered: SELENIUM
Process finished with exit code 0
在上一个示例中,我们在输入框中输入文本 selenium 的同时按下了 SHIFT 键,从而获得在大写字母格式的输入文本并在控制台中显示如下消息—— Text entered: SELENIUM 。
In the above example, we had entered the text selenium along with pressing SHIFT key in the input box and hence obtained the entered text in upper case with the message in the console − Text entered: SELENIUM.
最后,收到了消息 Process finished with exit code 0 ,表示代码成功执行。
Finally, the message Process finished with exit code 0 was received, signifying successful execution of the code.
Conclusion
这总结了我们对 Selenium Webdriver 操作类的教程的全面讲解。我们从描述操作类开始,讲解了操作类的各种方法以及演示如何执行单击、右键单击、双击、鼠标悬停、拖放和按键操作的示例以及 Selenium。这让你具备对操作类的深入了解。明智的做法是不断练习你学到的知识,并探索其他与 Selenium 相关的知识,以加深你的理解并拓展你的视野。
This concludes our comprehensive take on the tutorial on Selenium Webdriver Action Class. We’ve started with describing an Action class and walked through various methods of Action class, and examples illustrating how to perform click, right click, double click, mouse hovering, drag and drop, and key operation along with Selenium. This equips you with in-depth knowledge of the Action Class. It is wise to keep practicing what you’ve learned and exploring others relevant to Selenium to deepen your understanding and expand your horizons.