如何使用Java在Selenium WebDriver中打开新选项卡或如何使用Selenium WebDriver使用Action Class在Selenium中按Ctrl + T

时间:2019-05-06 10:56:08

标签: java selenium selenium-webdriver action

如何使用Java在Selenium Webdriver中按CTRL + T。 要么 如何使用Java在Selenium Webdriver中打开新标签。

[简单步骤: 1.打开google.com [不必触摸页面的任何元素/链接] 2.打开新标签页 3.打开yahoo.com

我尝试了动作课,但没有用

        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.yahoo.com/");
    System.out.println(driver.getTitle());

    driver.quit();

2 个答案:

答案 0 :(得分:2)

我尝试使用javascript和robot类。希望这会对您有所帮助。

JavaScript

   driver.get("http://www.google.com/");
   driver.manage().timeouts().pageLoadTimeout(30, TimeUnit.SECONDS);

   //Open new tab
   JavascriptExecutor jse = (JavascriptExecutor)driver;
   jse.executeScript("window.open()");

   //Switch to new tab 
   ArrayList<String> tabs = new ArrayList<String> (driver.getWindowHandles());
   driver.switchTo().window(tabs.get(1));
   driver.get("http://www.yahoo.com/");

机器人课程

    WebDriver driver = new ChromeDriver();
    driver.get("http://www.google.com");
    driver.manage().timeouts().pageLoadTimeout(30, TimeUnit.SECONDS);
    System.out.println(driver.getTitle());

    //Robot Class
    Robot r = new Robot();
    r.keyPress(KeyEvent.VK_CONTROL);
    r.keyPress(KeyEvent.VK_T);
    r.keyRelease(KeyEvent.VK_CONTROL);
    r.keyRelease(KeyEvent.VK_T);

    //Switch to new tab
    ArrayList<String> tabs = new ArrayList<String> (driver.getWindowHandles());
    driver.switchTo().window(tabs.get(1));
    driver.get("http://www.yahoo.com/");
    System.out.println(driver.getTitle());

答案 1 :(得分:-1)

此代码对我有效:

driver.get("http://www.google.com");

        String a = "window.open('https://www.yahoo.com', '_blank');";
        ((JavascriptExecutor)driver).executeScript(a);