从第二个窗口切换到第三个窗口时如何通过Selenium WebDriver处理多个窗口 - java

我正在尝试从第二个窗口切换到第三个窗口。但是无法处理第三个窗口。有人可以帮助我解决此问题。
我使用了比较窗口标题的逻辑,但是它不起作用。
代码=======================

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

Java-搜索字符串数组中的字符串 - java

在Java中,我们是否有任何方法可以发现特定字符串是字符串数组的一部分。我可以避免出现一个循环。例如String [] array = {"AA","BB","CC" }; string x = "BB" 我想要一个if (some condition to tell wheth…

将列表的python排序转换为Java代码。 - java

我正在尝试将将items列表排序为Java代码的python代码进行转换。如何在Java中进行这种排序?python code:import re items = ['10H', '10S', '2H', '3S', '4S', '6C',…

Java RegEx中的单词边界\ b - java

我在使用\b作为Java Regex中的单词定界符时遇到困难。对于text = "/* sql statement */ INSERT INTO someTable"; Pattern.compile("(?i)\binsert\b");找不到匹配项Pattern insPtrn = Pattern.compile(&…

如何避免用户输入中的撇号 - java

因此,我正在将信息从.csv文件导入数据库。但是我在csv文件中用户输入的描述遇到了麻烦,因为它们包含的单引号破坏了SQL导入。我的导入语句是字符串sqlJob ="INSERT INTO job (ID, Job_Contact, Internal_Comment, Customer_Name," + " Duration, …

Java Double与BigDecimal - java

我正在查看一些使用双精度变量来存储(360-359.9998779296875)结果为0.0001220703125的代码。 double变量将其存储为-1.220703125E-4。当我使用BigDecimal时,其存储为0.0001220703125。为什么将它双重存储为-1.220703125E-4? 参考方案 我不会在这里提及精度问题,而只会提及数字…