如何在从第二个切换到第三个 window 时通过 selenium webdriver 处理多个 windows

How to handle mutliple windows through selenium webdriver while switching from second to third window

我正在尝试从第二个 window 切换到第三个 window。但无法处理第三个 window.could 请有人帮我解决这个问题。 我使用了比较 window 标题的逻辑,但它不起作用。 代码=======================

package Package_1;
import static org.testng.Assert.assertEquals;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class Test_demo {
static WebDriver driver;

    public static void main(String[] args) throws InterruptedException {
        // TODO Auto-generated method stub
        System.setProperty("webdriver.chrome.driver","C:\Chrome\chromedriver_win32\chromedriver.exe");
        //System.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.Jdk14Logger");
     Thread.sleep(2000);
    ChromeOptions options = new ChromeOptions();
    Map<String, Object> prefs = new HashMap<String, Object>();
    prefs.put("credentials_enable_service", false);
    prefs.put("password_manager_enabled", false); 
      options.setExperimentalOption("prefs", prefs);
    options.addArguments("start-maximized");
    options.addArguments("disable-infobars");
    driver = new ChromeDriver(options);
    driver.get("http://www.universalmusic.com");
    driver.findElement(By.xpath(".//*[@id='main-menu-open']/span")).click();
    Thread.sleep(1000);
    driver.findElement(By.xpath(".//*[@id='main-menu-container']/div[2]/ul/li[3]/a/h3")).click();
    driver.findElement(By.xpath(".//*[@id='section-items']/div/ul/li[1]/a/div")).click();
    driver.findElement(By.xpath(".//*[@id='detail-main']/div[2]/ul/li/a")).click();
     Thread.sleep(2000);
     String MainWindow=driver.getWindowHandle();            
     System.out.println(MainWindow);

// To handle all new opened window.                        
   Set<String> s1=driver.getWindowHandles();
   System.out.println(s1);
Iterator<String> i1=s1.iterator();           

while(i1.hasNext())                    
{           
   String ChildWindow=i1.next();     
   System.out.println(ChildWindow);

   if(!MainWindow.equalsIgnoreCase(ChildWindow))                
   {              

           // Switching to Child window
           driver.switchTo().window(ChildWindow); 
//
      Thread.sleep(4000);
//        Actions act=new Actions(driver);
//        WebElement studio=driver.findElement(By.xpath("html/body/nav/div/ul[1]/li[1]/a"));
//        WebElement Studio_One=driver.findElement(By.xpath("html/body/div[2]/div/div[1]/ul/li[1]/ul/li[2]/a"));
//        act.moveToElement(studio).moveToElement(Studio_One).click().build().perform();
////          dElement(By.xpath("html/body/div[4]/main/div/section[3]/div/div/div[1]/div/a/div")).click();
      driver.findElement(By.xpath("html/body/nav/div/ul[1]/li[7]/a")).click();


    // String MainWindow1=driver.getWindowHandle();            

// To handle all new opened window.                        
   Set<String> s11=driver.getWindowHandles();
   System.out.println(s11);
Iterator<String> i11=s11.iterator();           

while(i11.hasNext())                    
{           
   String ChildWindow1=i11.next(); 

   System.out.println(ChildWindow1);

   if(!ChildWindow.equalsIgnoreCase(ChildWindow1))                
   {              

           // Switching to Child window
           driver.switchTo().window(ChildWindow1); 
           Thread.sleep(2000);
           driver.findElement(By.xpath(".//*[@id='col1']/div[2]/a")).click();
           driver.findElement(By.xpath(".//*[@id='email']")).sendKeys("");
           driver.findElement(By.xpath(".//*[@id='password']")).sendKeys("google@123");
           driver.findElement(By.xpath(".//*[@id='secureSignIn']/div[2]/form[1]/ul/button")).click();
           driver.findElement(By.xpath(".//*[@id='col1']/span")).click();
   }
//}
}


         }
         }
    }
}

错误堆栈跟踪:

Starting ChromeDriver 2.30.477700 (0057494ad8732195794a7b32078424f92a5fce41) on port 44071
Only local connections are allowed.
CDwindow-023c8c4f-3657-479e-9a5c-df3f71df5ba8
[CDwindow-023c8c4f-3657-479e-9a5c-df3f71df5ba8, CDwindow-493446dc-7c40-46d9-9779-287d9e58b346]
CDwindow-023c8c4f-3657-479e-9a5c-df3f71df5ba8
CDwindow-493446dc-7c40-46d9-9779-287d9e58b346
[CDwindow-023c8c4f-3657-479e-9a5c-df3f71df5ba8, CDwindow-493446dc-7c40-46d9-9779-287d9e58b346, CDwindow-d2de250e-1c80-44de-b589-0cdf1cb5b869]
CDwindow-023c8c4f-3657-479e-9a5c-df3f71df5ba8
Exception in thread "main" org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"xpath","selector":".//*[@id='col1']/div[2]/a"}
  (Session info: chrome=59.0.3071.86)
  (Driver info: chromedriver=2.30.477700 (0057494ad8732195794a7b32078424f92a5fce41),platform=Windows NT 10.0.14393 x86_64) (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 93 milliseconds
For documentation on this error, please visit: http://seleniumhq.org/exceptions/no_such_element.html
Build info: version: '2.53.0', revision: '35ae25b', time: '2016-03-15 17:00:58'
System info: host: 'D90ZC6Q1', ip: '192.168.163.235', os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '1.8.0_92'
Driver info: org.openqa.selenium.chrome.ChromeDriver
Capabilities [{applicationCacheEnabled=false, rotatable=false, mobileEmulationEnabled=false, networkConnectionEnabled=false, chrome={chromedriverVersion=2.30.477700 (0057494ad8732195794a7b32078424f92a5fce41), userDataDir=C:\Users\DAHIBH~1\AppData\Local\Temp\scoped_dir5596_14164}, takesHeapSnapshot=true, pageLoadStrategy=normal, databaseEnabled=false, handlesAlerts=true, hasTouchScreen=false, version=59.0.3071.86, platform=XP, browserConnectionEnabled=false, nativeEvents=true, acceptSslCerts=true, locationContextEnabled=true, webStorageEnabled=true, browserName=chrome, takesScreenshot=true, javascriptEnabled=true, cssSelectorsEnabled=true, unexpectedAlertBehaviour=}]
Session ID: b1584e7bbe2a8760b949629d4d5f0600
*** Element info: {Using=xpath, value=.//*[@id='col1']/div[2]/a}
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
    at java.lang.reflect.Constructor.newInstance(Unknown Source)
    at org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:206)
    at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:158)
    at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:678)
    at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:363)
    at org.openqa.selenium.remote.RemoteWebDriver.findElementByXPath(RemoteWebDriver.java:500)
    at org.openqa.selenium.By$ByXPath.findElement(By.java:361)
    at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:355)
    at Package_1.Test_demo.main(Test_demo.java:90)

这是切换到 Third Window 并单击 Login 按钮的完整代码块:

package demo;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
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 Q45455402_multiple_windows 
{

    static WebDriver driver;
    public static void main(String[] args) throws InterruptedException 
    {
        System.setProperty("webdriver.chrome.driver","C:\Utility\BrowserDrivers\chromedriver.exe");
        Map<String, Object> prefs = new HashMap<String, Object>();
        prefs.put("credentials_enable_service", false);
        prefs.put("password_manager_enabled", false); 
        ChromeOptions options = new ChromeOptions();
        options.setExperimentalOption("prefs", prefs);
        options.addArguments("start-maximized");
        options.addArguments("disable-infobars");
        options.addArguments("--disable-extensions");
        driver = new ChromeDriver(options);
        driver.get("http://www.universalmusic.com");
        driver.findElement(By.xpath("//a[@id='main-menu-open']/span")).click();
        WebDriverWait wait = new WebDriverWait(driver, 5);
        WebElement our_label = wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//div[@id='main-menu-container']//h3[contains(text(),'Our Labels')]")));
        our_label.click();
        JavascriptExecutor je = (JavascriptExecutor)driver;
        WebElement element = driver.findElement(By.xpath("//div[@id='section-items']/div[@class='items-container']//a[contains(@href,'http://www.universalmusic.com/label/abbey-road-studios/')]"));
        je.executeScript("arguments[0].scrollIntoView(true);",element);
        element.click();
        JavascriptExecutor je2 = (JavascriptExecutor)driver;
        WebElement element2 = driver.findElement(By.xpath("//div[@id='detail-main']//a[@class='button secondary links-button']"));
        je2.executeScript("arguments[0].scrollIntoView(true);",element2);
        String parent_window = driver.getWindowHandle();
        System.out.println("Parent Window ID is : "+parent_window);
        element2.click();
        Set<String> allWindows = driver.getWindowHandles();
        int count = allWindows.size();
        System.out.println("Now Total Windows : "+count);
        for(String child_1:allWindows)
            if(!parent_window.equalsIgnoreCase(child_1))
                driver.switchTo().window(child_1);
        System.out.println(driver.getTitle());
        String child1_window = driver.getWindowHandle();
        System.out.println("Child 1 Window ID is : "+child1_window);
        driver.findElement(By.linkText("Shop")).click();
        Set<String> all_Windows = driver.getWindowHandles();
        int count_final = all_Windows.size();
        System.out.println("Now Total Windows : "+count_final);
        for(String child_2:all_Windows)
            if(!parent_window.equalsIgnoreCase(child_2) && !child1_window.equalsIgnoreCase(child_2))
                driver.switchTo().window(child_2);
        String child2_window = driver.getWindowHandle();
        System.out.println("Child 2 Window ID is : "+child2_window);
        driver.findElement(By.xpath("//div[@id='col1']//a[@class='toggle login']")).click();
    }

}

我的 IDE 控制台上的输出是:

Parent Window ID is : CDwindow-4663fceb-a7a3-4d72-8236-510790729377
Now Total Windows : 2

Child 1 Window ID is : CDwindow-c5de0d53-06ab-4e27-9516-b9c7a130cd5f
Now Total Windows : 3
Child 2 Window ID is : CDwindow-e88831ba-6b53-449c-a2f2-b8ba341c8433