如何在同一个浏览器中打开多个标签? [英] How to open multiple tab in the same browser?

查看:312
本文介绍了如何在同一个浏览器中打开多个标签?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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"); 


    }

}

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

In my code I want to open two tabs in the same browser, but this code is opening only one tab. How do I open multiple tabs in the same browser?

推荐答案

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

You are not able to open Gmail in other tab because focus is still at 1st window, because selenium identifies a particular window to work with using its window handles hence you have to first switch that particular window using handle like: driver.switchTo().window(handle value)

这里是完整的代码:

 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"); 

}

这篇关于如何在同一个浏览器中打开多个标签?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆