如何使用Selenium WebDriver在新标签页(chrome)中打开链接?

时间:2016-01-16 16:34:22

标签: java google-chrome selenium selenium-webdriver browser-tab

System.setProperty("webdriver.chrome.driver", "D:\\softwares\\chromedriver_win32\\chromedriver.exe");

WebDriver driver = new ChromeDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.manage().window().maximize();
driver.get("https://mail.google.com/");
String selectLinkOpeninNewTab = Keys.chord(Keys.CONTROL,Keys.RETURN); 
driver.findElement(By.linkText("www.facebook.com")).sendKeys(selectLinkOpeninNewTab);

新标签正在打开,但网址链接未打开。

14 个答案:

答案 0 :(得分:18)

以下代码适用于Selenium 3和chrome版本58。

    WebDriver driver = new ChromeDriver();
    driver.get("http://yahoo.com");  
    ((JavascriptExecutor)driver).executeScript("window.open()");
    ArrayList<String> tabs = new ArrayList<String>(driver.getWindowHandles());
    driver.switchTo().window(tabs.get(1));
    driver.get("http://google.com");

答案 1 :(得分:11)

我检查了下面的代码,它对我来说很好。我从here找到了答案。

    driver = new ChromeDriver();
    driver.manage().window().maximize();

    baseUrl = "http://www.google.co.uk/";
    driver.get(baseUrl);
    driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL +"t");

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

    driver.switchTo().window(tabs.get(0)); // switch back to main screen        
    driver.get("https://www.news.google.com");

答案 2 :(得分:5)

我尝试了其他技术,但是它们都不起作用,也没有产生错误,但是当我使用下面的代码时,它对我有用。

((JavascriptExecutor)driver).executeScript("window.open()");
ArrayList<String> tabs = new ArrayList<String>(driver.getWindowHandles());
driver.switchTo().window(tabs.get(1));
driver.get("http://google.com");

答案 3 :(得分:1)

首先使用 Ctrl + t 键打开空的新Tab,然后使用.get()获取所需的URL。你的代码应该是这样的 -

String selectLinkOpeninNewTab = Keys.chord(Keys.CONTROL,"t");
driver.findElement(By.tagName("body")).sendKeys(selectLinkOpeninNewTab);

driver.get("www.facebook.com");

如果要在新选项卡中打开当前视图的链接,则可以使用上面编写的代码。而不是By.linkText(),而是确保使用适当的By选择器类来选择Web元素。

答案 4 :(得分:1)

我使用下面的代码在浏览器中使用C#selenium打开一个新标签..

IJavaScriptExecutor js = (IJavaScriptExecutor)driver;

js.ExecuteScript("window.open();");

答案 5 :(得分:1)

Selenium 4 is already included this feature now, you can directly 
open new Tab or new Window with any URL. 

WebDriverManager.chromedriver().setup();

driver = new ChromeDriver(options);

driver.get("www.Url1.com");     
//  below code will open Tab for you as well as switch the control to new Tab
driver.switchTo().newWindow(WindowType.TAB);

// below code will navigate you to your desirable Url 
driver.get("www.Url2.com");

download Maven dependencies, this is what I downloaded - 

        <dependency>
            <groupId>io.github.bonigarcia</groupId>
            <artifactId>webdrivermanager</artifactId>
            <version>3.7.1</version>
        </dependency>
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.6</version>
        </dependency> 

    you can refer: https://codoid.com/selenium-4-0-command-to-open-new-window-tab/

    watch video : https://www.youtube.com/watch?v=7SpCMkUKq-Y&t=8s

google out for - WebDriverManager selenium 4

答案 6 :(得分:0)

Selenium只能在浏览器的WebElements上自动执行。打开新选项卡是在webBrowser上执行的操作,这是一个独立的应用程序。为此,您可以使用java.util。*包中的Robot类,该类可以使用键盘执行操作,无论它是什么类型的应用程序。 所以,这是您的操作代码。 请注意,您无法使用Robot类自动化独立应用程序,但您可以执行键盘或鼠标操作

System.setProperty("webdriver.chrome.driver","softwares\\chromedriver_win32\\chromedriver.exe"); 
WebDriver driver = new ChromeDriver();
driver.manage().timeouts().implicitlyWait(20,TimeUnit.SECONDS);
driver.manage().window().maximize();
driver.get("http://www.google.com");
Robot rob = new Robot();
rob.keyPress(keyEvent.VK_CONTROL);
rob.keyPress(keyEvent.VK_T);
rob.keyRelease(keyEvent.VK_CONTROL);
rob.keyRelease(keyEvent.VK_T);

在此步骤之后,您将需要一个窗口迭代器来切换到新选项卡:

Set <String> ids = driver.getWindowHandles();
Iterator <String> it = ids.iterator();
String currentWindow = it.next();
String newWindow = it.next();
driver.switchTo().window(newWindow);
driver.findElement(By.linkText("www.facebook.com")).sendKeys(selectLinkOpeninNewTab);

答案 7 :(得分:0)

如果可以获取链接元素,则可以使用它。还将带您进入打开的选项卡。

WebElement link= driver.findElement(By.tagname("a"));  
String keyString =   Keys.CONTROL+Keys.SHIFT.toString()+Keys.ENTER.toString());
link.sendKeys(keyString);

答案 8 :(得分:0)

我想对我的小儿子做一个机器人,只是播放一个Youtube视频,然后展示一个机器人跳舞。

由于某种原因,上面解释的CONTROL + T之类的命令对我不起作用,也许不是正确的答案,但是我使用如下这样的自定义Javascript脚本解决了我的问题:

using (var driver = new ChromeDriver())
            {
                var link1 = "https://www.youtube.com/watch?v=0GIgk4yuHOQ";
                //open a music
                driver.Navigate().GoToUrl(link1);
                var link2 = "https://images-wixmp-ed30a86b8c4ca887773594c2.wixmp.com/f/fbe53d6d-c13f-4eec-9bcf-62f19cfab15a/d4m0h4v-9442b1f2-6a49-4818-8f51-5ebe216f043c.gif?token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJ1cm46YXBwOjdlMGQxODg5ODIyNjQzNzNhNWYwZDQxNWVhMGQyNmUwIiwic3ViIjoidXJuOmFwcDo3ZTBkMTg4OTgyMjY0MzczYTVmMGQ0MTVlYTBkMjZlMCIsImF1ZCI6WyJ1cm46c2VydmljZTpmaWxlLmRvd25sb2FkIl0sIm9iaiI6W1t7InBhdGgiOiIvZi9mYmU1M2Q2ZC1jMTNmLTRlZWMtOWJjZi02MmYxOWNmYWIxNWEvZDRtMGg0di05NDQyYjFmMi02YTQ5LTQ4MTgtOGY1MS01ZWJlMjE2ZjA0M2MuZ2lmIn1dXX0.BTTlingNpBqH5O9dNVienFsArNqkfUc7KXnIgHumrBQ";
                //Dance robot, dance
                driver.ExecuteScript($"window.open('{link2}', '_blank');");
                Thread.Sleep(20000);
            }

答案 9 :(得分:0)

要点击预期会从新标签页打开的链接,请使用此

WebDriver driver = new ChromeDriver(); 
driver.get("https://www.yourSite.com"); 
WebElement link=driver.findElement(By.xpath("path_to_link")); 

Actions actions = new Actions(driver); 
actions.keyDown(Keys.LEFT_CONTROL) 
       .click(element) 
       .keyUp(Keys.LEFT_CONTROL) 
       .build() 
       .perform(); 

ArrayList<String> tab = new ArrayList<>(driver.getWindowHandles()); 
driver.switchTo().window(tab.get(1));

答案 10 :(得分:0)

使用Selenium WebDriver可以通过多种方式在新标签页中打开链接。


用例A:打开一个相邻的空白标签并通过迭代器进行迭代

  • 代码块:

    import java.util.Iterator;
    import java.util.Set;
    
    import org.openqa.selenium.JavascriptExecutor;
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.chrome.ChromeDriver;
    import org.openqa.selenium.chrome.ChromeOptions;
    import org.openqa.selenium.support.ui.ExpectedConditions;
    import org.openqa.selenium.support.ui.WebDriverWait;
    
    public class NewTab_blank_iterator {
    
        public static void main(String[] args) {
    
            System.setProperty("webdriver.chrome.driver","C:\\WebDrivers\\chromedriver.exe");
            ChromeOptions options = new ChromeOptions();
            options.addArguments("start-maximized");
            WebDriver driver =  new ChromeDriver(options); 
            driver.get("https://mail.google.com/");
            String firstWindowHandle = driver.getWindowHandle();
            System.out.println("First Window Handle is: "+firstWindowHandle);
            // Opening an adjacent blank tab
            ((JavascriptExecutor)driver).executeScript("window.open('','_blank');");
            new WebDriverWait(driver, 10).until(ExpectedConditions.numberOfWindowsToBe(2));
            Set<String> allWindowHandles = driver.getWindowHandles();
            // Using iterator
            Iterator<String> itr = allWindowHandles.iterator();
            while(itr.hasNext()) {
                String nextWindow = itr.next();
                if(!firstWindowHandle.equalsIgnoreCase(nextWindow)) {
                    driver.switchTo().window(nextWindow);
                    System.out.println("New Tab Window Handle is: "+nextWindow);
                }
            }
        }
    }
    
  • 控制台输出:

    First Window Handle is: CDwindow-0D89767363ED691767000F01E6712D0B
    New Tab Window Handle is: CDwindow-7232D2058514ED22344F129D30A0CCE7
    
  • 浏览器快照:

blank_tab


用例B:打开带有url的相邻标签并通过迭代器进行迭代

  • 代码块:

    import java.util.Iterator;
    import java.util.Set;
    
    import org.openqa.selenium.JavascriptExecutor;
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.chrome.ChromeDriver;
    import org.openqa.selenium.chrome.ChromeOptions;
    import org.openqa.selenium.support.ui.ExpectedConditions;
    import org.openqa.selenium.support.ui.WebDriverWait;
    
    public class NewTab_url_forLoop {
    
        public static void main(String[] args) {
    
            System.setProperty("webdriver.chrome.driver","C:\\WebDrivers\\chromedriver.exe");
            ChromeOptions options = new ChromeOptions();
            options.addArguments("start-maximized");
            WebDriver driver =  new ChromeDriver(options); 
            String url1 = "https://mail.google.com/";
            String url2 = "https://www.facebook.com/";
            driver.get(url1);
            String firstWindowHandle = driver.getWindowHandle();
            System.out.println("First Window Handle is: "+firstWindowHandle);
            // Opening Facebook in the adjacent TAB
            ((JavascriptExecutor)driver).executeScript("window.open('" + url2 +"');");
            new WebDriverWait(driver, 10).until(ExpectedConditions.numberOfWindowsToBe(2));
            Set<String> allWindowHandles = driver.getWindowHandles();
            // Using iterator
            Iterator<String> itr = allWindowHandles.iterator();
            while(itr.hasNext()) {
                String nextWindow = itr.next();
                if(!firstWindowHandle.equalsIgnoreCase(nextWindow)) {
                    driver.switchTo().window(nextWindow);
                    System.out.println("New Tab Window Handle is: "+nextWindow);
                }
            }
        }
    }
    
  • 控制台输出:

    First Window Handle is: CDwindow-01F5622275A2EA2C1ABE2F0CDEB3D09B
    New Tab Window Handle is: CDwindow-9E3349B91FB2FA4D5B7D4A90D0E87BD3
    
  • 浏览器快照:

url_tab

答案 11 :(得分:0)

在选项卡之间切换时,操作类并非始终在所有浏览器和所有Webdriver上均有效。最好的方法是使用机器人类。试试这个代码。

        String website = "https://www.google.com";
        String website1 = "https://www.msn.com/en-in/";
        String controlpath = "C:\\Libraries\\msedgedriver.exe";
        System.setProperty("webdriver.edge.driver", controlpath);
        driver = new EdgeDriver();
        driver.manage().window().maximize(); //  Maximize browser
        driver.get(website);
        System.out.println("Google page");
        
        Robot robot = new Robot();                          
        robot.keyPress(KeyEvent.VK_CONTROL); 
        robot.keyPress(KeyEvent.VK_T); 
        robot.keyRelease(KeyEvent.VK_CONTROL); 
        robot.keyRelease(KeyEvent.VK_T);
        
        //Switch focus to new tab
        ArrayList<String> tabs = new ArrayList<String> (driver.getWindowHandles());
        //System.out.println("Handle info"+ driver.getWindowHandles());
        driver.switchTo().window(tabs.get(1));
    
        //Launch URL in the new tab
        driver.get(website1);
        System.out.println("msn page");
        Thread.sleep(5000);
        driver.switchTo().window(tabs.get(0));
        Thread.sleep(5000);

答案 12 :(得分:0)

原始海报询问如何在新标签页上打开链接。所以这就是我在C#中完成的方式。

        IWebDriver driver = new ChromeDriver();
        driver.Manage().Window.Maximize();
        driver.Navigate().GoToUrl("https://microsoft.com");
        IWebElement eventlink = driver.FindElement(By.Id("uhfLogo"));
        Actions action = new Actions(driver);
        action.KeyDown(Keys.Control).MoveToElement(eventlink).Click().Perform(); 

这实际上是对所选元素执行Control + Click,以便在新标签页中打开链接。

答案 13 :(得分:-2)

您可以使用以下代码打开多个浏览器或窗口:

WebDriver driver = new ChromeDriver();
driver.get("http://yahoo.com");  

WebDriver driver1 = new ChromeDriver();
driver1.get("google.com");

WebDriver driver2 = new InternetExplorerDriver();
driver2.get("google.com/gmap");