环境
selenium:3.141.59
java:jdk1.8
效果
在使用selenium
进行一些自动化工作时,我们可能会遇到需要以新标签页的形式打开链接的场景,要实现这个功能有两种办法,这里主要记录selenium
中的Actions类配合Java中的Robot
类的实现方式。最终效果如下:

实现
思路一 模拟操作
通过selenium
定位到页面元素,再通过Actions
类实现鼠标右键,但是selenium
并不能继续操作我们右键出来的菜单,当然也可以通过Actions
中提供的鼠标移动方法,但是在真实环境下很难精准定位到鼠标应该移动到的位置,既然selenium
的本质就是模拟用户操作,那同样的,在Java
的Robot
类也为我们提供了模拟用户操作的相关API,我们可以通过Robot
类来模拟键盘的上下选择
和回车
,以达到右键菜单的选择。代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
| package com.yousan;
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.awt.*; import java.awt.event.KeyEvent;
public class App { public static void main(String[] args) throws InterruptedException, AWTException { WebDriver driver = new ChromeDriver(); driver.get("http://baidu.com"); Thread.sleep(2000L); WebElement logo = driver.findElement(By.cssSelector("#s_lg_img")); Actions actions = new Actions(driver); actions.contextClick(logo).perform(); Robot robot = new Robot(); robot.keyPress(KeyEvent.VK_DOWN); robot.keyRelease(KeyEvent.VK_DOWN); Thread.sleep(1000L); robot.keyPress(KeyEvent.VK_ENTER); robot.keyRelease(KeyEvent.VK_ENTER); } }
|
思路二 使用JS
除了通过模拟真实的交互操作外,在实现以新标签页打开链接的这个需求上,我们还可以直接通过js代码来实现,代码如下:
1 2 3
| WebDriver driver = new ChromeDriver(); ((JavascriptExecutor) driver).executeAsyncScript("window.open('http://baidu.com')");
|