java - 如何使用 Java 在 selenium WebDriver 中按 CTRL+T 和 CTRL+TAB?

标签 java selenium selenium-webdriver webdriver

Hi All,

For one of my project I need to open a new tab and navigate between the tabs for the same I need to know how can I press CTRL+T and CTRL+TAB in Selenium Webdriver using Java.

Please let me know how can I do the same.Thank You...!!!

I'm using the below:

Firefox Version: 48.0.2

Java Version: 1.8

Selenium WebDriver Version: 3.0.0

OS: Windows 10

我试过下面的代码,但它似乎不起作用:

import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class Handling_Tabs {

    public static void main(String[] args) {
        System.setProperty("webdriver.gecko.driver","C:\\Eclipse\\Drivers\\geckodriver.exe");
        WebDriver driver = new FirefoxDriver();
        driver.get("http://www.google.com/");
        System.out.println(driver.getTitle());
        driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL+"t");
        driver.get("http://www.bing.com/");
        System.out.println(driver.getTitle());
        driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL+"\t");
        System.out.println(driver.getTitle());      
    }
}

最佳答案

您可以为 Ctrl+tCTRL+TAB 使用 Actions 类。我修改了你的例子,如下所示

@Test
public void OpeningNewTab(){
    WebDriver driver = new FirefoxDriver();
    driver.get("http://www.google.com/");
    driver.manage().timeouts().pageLoadTimeout(30, TimeUnit.SECONDS);
    System.out.println(driver.getTitle());
    Actions act = new Actions(driver);
    act.keyDown(Keys.CONTROL).sendKeys("t").keyUp(Keys.CONTROL).build().perform();
    driver.get("http://www.bing.com/");
    System.out.println(driver.getTitle());
    act.keyDown(Keys.CONTROL).sendKeys("t").keyUp(Keys.CONTROL).build().perform();
    driver.get("http://www.yahoo.com/");
    System.out.println(driver.getTitle());
    driver.close();
    driver.quit();

}

关于java - 如何使用 Java 在 selenium WebDriver 中按 CTRL+T 和 CTRL+TAB?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39338773/

相关文章:

java - 为什么 Selenium 在每个 JUnit 测试项之间创建一个新的 RC 和/或浏览器实例?

javascript - Python Selenium : How to get text generated by JavaScript in input field

python - Selenium 远程 WebDriver

java - 查找我的组件是否是其他组件的祖先

java - Android 缺少 android.net.StaticIpConfiguration。无法设置新实例或导入

java - 使用 struts2 操作处理许多并发的 AJAX 请求

java - 如何使用 Java 在 Selenium RC 中使用 xpath

java - maven:将资源从依赖 jar 复制到目标文件夹

java - 想要在 Selenium 中创建一个计时器并执行一些操作,直到达到定义的时间段

ruby - 如何使用带有 ruby​​ 的 selenium-webdriver 滚动元素