“切换到"方法不适用于切换到浏览器中的标签页

问题描述:

我正在使用下面的代码来测试窗口句柄.

I am using below code to test window handle.

新页面在新选项卡中打开,但是switchTo命令不会切换到该页面.

New page opens in new tab but switchTo command do not switch to it.

public static void main(String[] args) {
        Actions act = new Actions(driver);
        driver.get("https://www.google.co.in");

        String parentWin = driver.getWindowHandle();
        act.keyDown(Keys.LEFT_CONTROL).perform();
        driver.findElement(By.linkText("Images")).click();

        for(String newWindow: driver.getWindowHandles()){
            driver.switchTo().window(newWindow);
            driver.findElement(By.id("lst-ib")).sendKeys("hello world");
            driver.findElement(By.name("btnG")).click();
            driver.close();
        }


        driver.switchTo().window(parentWin);
        driver.findElement(By.linkText("Gmail")).click();


    }

此代码在此处被投票为正确答案:如何处理Java使用Selenium WebDriver中的新窗口?来自@CODEBLACK

This code voted as correct answer here: How to handle the new window in Selenium WebDriver using Java? from @CODEBLACK

我对此的理解是每个驱动程序实例都是浏览器,而不是选项卡.但是...当我查看如何执行此操作时,我看到代码示例指出您的代码应该可以工作.因此,我不确定它是否曾经工作过并且现在不起作用,或者他们说的是选项卡,但意味着新的浏览器窗口...无论哪种方式,我都找到了解决方案.有两种方法可以做到这一点.

My understanding of how this works is that each driver instance is a browser, not a tab. But... when I looked up how to do this I see code samples that state that your code should work. So I'm not sure if it used to work and doesn't now or if they were saying tabs but meant new browser windows... either way, I found a solution. There are two ways to do this.

  1. 在新的浏览器窗口而不是选项卡中打开新页面.这是一个简单的解决方案...您只需将CTRL键更改为SHIFT键即可.

  1. Open the new page in a new browser window instead of a tab. This is an easy fix... you just change your CTRL keypress to a SHIFT.

act.keyDown(Keys.SHIFT).perform();

act.keyDown(Keys.SHIFT).perform();

我没有尝试过的另一种方法,但是在下面的链接中对此进行了描述.它基本上涉及使用CTRL + TAB键盘快捷键在打开的选项卡之间移动.您将不得不跟踪自己的位置,并且根据打开的选项卡的数量,这可能会很快变得很毛茸茸.

The other way I haven't tried but it is described in the link below. It basically involves using the CTRL+TAB keyboard shortcut to move through the open tabs. You are going to have to track where you are and depending on the number of open tabs, this could get pretty hairy pretty fast.

http://design-interviews.blogspot.com/2014/11/switching-between-tabs-in-same-browser-window.html

我建议使用#1,因为它不太容易破解,但您可能需要将其在选项卡中打开并必须与#2配合使用.

I would recommed #1 because it feels less hacky but you may have a requirement that it opens in a tab and have to go with #2.