如何在同一个浏览器中打开多个标签?

时间:2017-03-20 08:44:11

标签: java selenium selenium-webdriver

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

public class newtab {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        String driverpath = "geckodriver path\\";
        System.setProperty("webdriver.gecko.driver",driverpath+"geckodriver.exe");
        WebDriver driver = new FirefoxDriver();
        driver.get("https://www.google.com");
        driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL + "t");
        driver.get("http://www.gmail.com"); 


    }

}

在我的代码中,我想在同一个浏览器中打开两个选项卡,但此代码只打开一个选项卡。如何在同一浏览器中打开多个标签?

3 个答案:

答案 0 :(得分:2)

您无法在其他标签中打开Gmail,因为焦点仍在第一个窗口,因为selenium使用其窗口句柄标识要使用的特定窗口,因此您必须首先使用以下句柄切换该特定窗口:driver.switchTo ()。窗口(句柄值)

这是完整的代码:

 public static void main(String[] args) {

    System.setProperty("webdriver.chrome.driver", "c:\\SRP\\chromedriver.exe");

    WebDriver driver = new ChromeDriver();
    driver.get("https://www.google.com");

    String newTab =null;
    String baseTab = driver.getWindowHandle();

    driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL + "t");

    Set <String> allTabs = driver.getWindowHandles();

    allTabs.remove(baseTab);

    Iterator<String> itr = allTabs.iterator();

    while(itr.hasNext()){


    newTab = (String) itr.next();

    }

    driver.switchTo().window(newTab);
    driver.get("http://www.gmail.com"); 

}

答案 1 :(得分:1)

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

public class NewTab {

    public static void main(String[] args) throws AWTException {
        System.setProperty("webdriver.gecko.driver", "C:\\Users\\User-024\\Downloads\\geckodriver.exe");
        WebDriver driver = new FirefoxDriver();
        driver.get("https://www.google.com");
        String parent = driver.getWindowHandle();

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

        Set<String> browsers = driver.getWindowHandles();
        for (String i : browsers) {
            if (!i.equals(parent)) {
                driver.switchTo().window(i);
                driver.get("http://www.gmail.com");
            }
        }
    }
}

此代码对我有用。

答案 2 :(得分:0)

我编写了简单的代码,它对我有用。它在同一浏览器的不同选项卡中打开两个不同的URL。

public void cls(){
    WebDriver driver = new FirefoxDriver();

driver.get("http://google.com");
String baseTab = driver.getWindowHandle();
driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL + "t");
driver.get("http://gmail.com"); 

}