下拉菜单并切换到Selenium Webdriver中的新窗口无法在Firefox中运行

时间:2014-12-17 07:08:30

标签: java javascript eclipse firefox selenium

我正在尝试通过我的开发人员登录www.salesforce.com自动化几个网页,即创建案例,创建帐户和联系人。我正在使用Mozilla Firefox 34.0.5以及Eclipse Luna和Java来使用Selenium WebDriver进行自动化。我也在使用JExcel API从硬盘中的excel文件中读取数据。系统规格是Windows7旗舰版32位。

我的自动化代码适用于谷歌浏览器,但在Firefox中网页上的某些字段,如下拉菜单框,弹出窗口和放大器切换控件到新的弹出窗口不起作用。我没有找到解决这个问题的方法。我无法理解selenium命令失败的原因:" selectByVisibleText(String)"。

  1. 显示下拉菜单列表,同时突出显示指定的选项,但中止单击/选择操作并选择默认值。

  2. 使用弹出窗口,selenium命令:" driver.switchTo()。window(windowhandle)"不管用。将打开新的弹出窗口并生成窗口句柄,但显示的错误是"无法找到窗口{window Handle String}"。

  3. 我无法弄清楚为什么它不能通过窗口句柄定位窗口并在Firefox中切换到它,如果它在其他浏览器中正常工作?

    以下是我的完整代码

    public class PoiExcelCase {
    
        WebDriver driver;
        FileInputStream fis;
        HSSFWorkbook wb;
        HSSFSheet sh;
    
        @BeforeTest
        public void login() throws BiffException, IOException
        {
            driver = new FirefoxDriver();
            //System.setProperty("webdriver.chrome.driver", "D:/chromedriver_win32/chromedriver.exe");
            //driver = new ChromeDriver();
    
            driver.manage().window().maximize();
            driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
            fis = new FileInputStream(new File("D:/Salesforce.xls"));
            wb = new HSSFWorkbook(fis);
            sh = wb.getSheet("Sheet1");
            driver.navigate().to("http://www.salesforce.com/in/?ir=1");
            driver.findElement(By.xpath(".//*[@id='button-login']")).click();
            driver.findElement(By.xpath(".//*[@id='username']")).sendKeys(sh.getRow(1).getCell(0).getStringCellValue());
            driver.findElement(By.xpath(".//*[@id='password']")).sendKeys(sh.getRow(1).getCell(1).getStringCellValue());
            driver.findElement(By.xpath(".//*[@id='Login']")).click();
        }
    
        @Test
        public void caseSF() throws InterruptedException 
        {
              driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
              sh = wb.getSheet("Sheet4");
              WebElement we;
              String str;
              we = driver.findElement(By.xpath(".//*[@id='tsidLabel']"));
    
              if(we.getText().equals("Sales")==false)
              {
                we.click();
                driver.findElement(By.xpath(".//*[@id='tsid-menuItems']/a[text()='Sales']")).click();
              }
    
                driver.findElement(By.xpath(".//*[@id='Case_Tab']/a")).click();
                driver.findElement(By.name("new")).click();
                driver.findElement(By.xpath(".//*[@id='cas3_lkwgt']/img")).click();
                Thread.sleep(10000);
                String mainwindow = driver.getWindowHandle();
    
                Set<String> winhandles = driver.getWindowHandles();
                System.out.println(winhandles.size());
                for(String st : winhandles)
                {
                    System.out.println(st);
                    driver.switchTo().window(st);
                    Thread.sleep(5000);
                    System.out.println(driver.getTitle());
                }
                /*
                Set<String> s = driver.getWindowHandles();
                Iterator<String> ite = s.iterator();
                while(ite.hasNext())
                {
                    String popup = ite.next();
                    if(!popup.equalsIgnoreCase(mainwindow))
                        driver.switchTo().window(popup);
                }
                */
                try
                {
                    driver.switchTo().frame("resultsFrame");
                    driver.findElement(By.linkText("Suresh Verma")).click();
                    driver.switchTo().window(mainwindow);
                    Thread.sleep(5000);
                    str = driver.findElement(By.xpath(".//*[@id='cas4']")).getAttribute("value");
                    System.out.println(str);
                    try
                    {
                        Assert.assertEquals(str, sh.getRow(2).getCell(2).getStringCellValue());
                    }
                    catch(Throwable e)
                    {
                        System.out.println("Incorrect Account Name");
                    }
                }
                catch(Exception e)
                {
                    System.out.println("I am in catch block");
                    driver.close();
                    driver.switchTo().window(mainwindow);
                    driver.findElement(By.xpath(".//*[@id='cas3']")).sendKeys(sh.getRow(2).getCell(1).getStringCellValue());
                    driver.findElement(By.xpath(".//*[@id='cas4']")).sendKeys(sh.getRow(2).getCell(2).getStringCellValue());
                }
    
                we = driver.findElement(By.xpath(".//*[@id='cas5']"));
                we.click();
                Select se;
                se = new Select(we);
                se.selectByVisibleText(sh.getRow(2).getCell(3).getStringCellValue());
    
                we = driver.findElement(By.xpath(".//*[@id='cas6']"));
                se = new Select(we);
                we.click();
                se.selectByVisibleText(sh.getRow(2).getCell(4).getStringCellValue());
    
                we = driver.findElement(By.xpath(".//*[@id='cas7']"));
                se = new Select(we);
                we.click();
                se.selectByVisibleText(sh.getRow(2).getCell(5).getStringCellValue());
    
                we = driver.findElement(By.xpath(".//*[@id='cas8']"));
                se = new Select(we);
                we.click();
                se.selectByVisibleText(sh.getRow(2).getCell(6).getStringCellValue());
    
                we = driver.findElement(By.xpath(".//*[@id='cas11']"));
                se = new Select(we);
                we.click();
                se.selectByVisibleText(sh.getRow(2).getCell(7).getStringCellValue());
    
                we = driver.findElement(By.xpath(".//*[@id='00N9000000Ctc7c']"));
                se = new Select(we);
                we.click();
                se.selectByVisibleText(sh.getRow(2).getCell(8).getStringCellValue());
    
                we = driver.findElement(By.xpath(".//*[@id='00N9000000Ctc7b']"));
                se = new Select(we);
                we.click();
                se.selectByVisibleText(sh.getRow(2).getCell(9).getStringCellValue());
    
                driver.findElement(By.xpath(".//*[@id='00N9000000Ctc7a']")).sendKeys(sh.getRow(2).getCell(10).getStringCellValue());
    
                we = driver.findElement(By.xpath(".//*[@id='00N9000000Ctc7d']"));
                se = new Select(we);
                we.click();
                se.selectByVisibleText(sh.getRow(2).getCell(11).getStringCellValue());
    
                driver.findElement(By.xpath(".//*[@id='cas14']")).sendKeys(sh.getRow(2).getCell(12).getStringCellValue());
                driver.findElement(By.xpath(".//*[@id='cas15']")).sendKeys(sh.getRow(2).getCell(13).getStringCellValue());
                driver.findElement(By.xpath(".//*[@id='cas16']")).sendKeys(sh.getRow(2).getCell(14).getStringCellValue());
    
                if(sh.getRow(2).getCell(15).getStringCellValue().equalsIgnoreCase("Yes"))
                    driver.findElement(By.xpath(".//*[@id='cas21']")).click();
                if(sh.getRow(2).getCell(16).getStringCellValue().equalsIgnoreCase("Yes"))
                    driver.findElement(By.xpath(".//*[@id='cas22']")).click();
    
                driver.findElement(By.xpath(".//*[@id='bottomButtonRow']/input[1]")).click();
                Thread.sleep(3000);
                driver.findElement(By.xpath(".//span[text()='Details']")).click();
    
                Point pt = driver.findElement(By.xpath(".//*[@id='bodyTable']/tbody/tr/td/div/div[3]")).getLocation();
                ((JavascriptExecutor)driver).executeScript("window.scrollBy(0,"+pt.getY()+");");
                Thread.sleep(10000);
    
                driver.findElement(By.xpath(".//*[@id='topButtonRow']/input[4]")).click();
    
                Alert alert = driver.switchTo().alert();
                alert.accept();
    
                //driver.findElement(By.xpath(".//input[@name='cancel']")).click();
    
        }
    
        @AfterTest
        public void logout() throws InterruptedException 
        {
            driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
            driver.findElement(By.xpath(".//span[@id='userNavLabel']")).click();
            driver.findElement(By.xpath(".//a[text()='Logout']")).click();
            Thread.sleep(3000);
            driver.close();
        }
    
    }
    

    在Firefox中执行时显示的输出如下:

    [TestNG] Running:
      C:\Users\psit\AppData\Local\Temp\testng-eclipse--1537148127\testng-customsuite.xml
    
    2
    {2cba4b8b-1677-425e-8d8c-a153c500d5a4}
    Case Edit: New Case ~ salesforce.com - Developer Edition
    {07c35b20-263d-4a1a-9e4e-c6a4be6e1162}
    FAILED: caseSF
    org.openqa.selenium.NoSuchWindowException: Unable to locate window "{07c35b20-263d-4a1a-9e4e-c6a4be6e1162}"
    Command duration or timeout: 2.08 seconds
    Build info: version: '2.44.0', revision: '76d78cf', time: '2014-10-23 20:03:00'
    System info: host: 'USER2', ip: '192.168.1.102', os.name: 'Windows 7', os.arch: 'x86', os.version: '6.1', java.version: '1.8.0_25'
    Driver info: org.openqa.selenium.firefox.FirefoxDriver
    Capabilities [{applicationCacheEnabled=true, rotatable=false, handlesAlerts=true, databaseEnabled=true, version=34.0.5, platform=WINDOWS, nativeEvents=false, acceptSslCerts=true, webStorageEnabled=true, locationContextEnabled=true, browserName=firefox, takesScreenshot=true, javascriptEnabled=true, cssSelectorsEnabled=true}]
    Session ID: 5e1ead01-1d29-4c4a-9821-729b1768547e
        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:204)
        at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:156)
        at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:599)
        at org.openqa.selenium.remote.RemoteWebDriver$RemoteTargetLocator.window(RemoteWebDriver.java:882)
        at apache_poi.PoiExcelCase.caseSF(PoiExcelCase.java:79)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
        at java.lang.reflect.Method.invoke(Unknown Source)
        at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:84)
        at org.testng.internal.Invoker.invokeMethod(Invoker.java:714)
        at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:901)
        at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1231)
        at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:127)
        at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:111)
        at org.testng.TestRunner.privateRun(TestRunner.java:767)
        at org.testng.TestRunner.run(TestRunner.java:617)
        at org.testng.SuiteRunner.runTest(SuiteRunner.java:334)
        at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:329)
        at org.testng.SuiteRunner.privateRun(SuiteRunner.java:291)
        at org.testng.SuiteRunner.run(SuiteRunner.java:240)
        at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
        at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)
        at org.testng.TestNG.runSuitesSequentially(TestNG.java:1224)
        at org.testng.TestNG.runSuitesLocally(TestNG.java:1149)
        at org.testng.TestNG.run(TestNG.java:1057)
        at org.testng.remote.RemoteTestNG.run(RemoteTestNG.java:111)
        at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:204)
        at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:175)
    Caused by: org.openqa.selenium.NoSuchWindowException: Unable to locate window "{07c35b20-263d-4a1a-9e4e-c6a4be6e1162}"
    Build info: version: '2.44.0', revision: '76d78cf', time: '2014-10-23 20:03:00'
    System info: host: 'USER2', ip: '192.168.1.102', os.name: 'Windows 7', os.arch: 'x86', os.version: '6.1', java.version: '1.8.0_25'
    Driver info: driver.version: unknown
        at <anonymous class>.nsCommandProcessor.prototype.switchToWindow(file:///C:/Users/psit/AppData/Local/Temp/anonymous5017770494986140267webdriver-profile/extensions/fxdriver@googlecode.com/components/command-processor.js:11725:19)
        at <anonymous class>.nsCommandProcessor.prototype.switchToWindow/<(file:///C:/Users/psit/AppData/Local/Temp/anonymous5017770494986140267webdriver-profile/extensions/fxdriver@googlecode.com/components/command-processor.js:11729:9)
    
    
    ===============================================
        Default test
        Tests run: 1, Failures: 1, Skips: 0
    ===============================================
    
    
    ===============================================
    Default suite
    Total tests run: 1, Failures: 1, Skips: 0
    ===============================================
    
    [TestNG] Time taken by org.testng.reporters.SuiteHTMLReporter@1192d32: 142 ms
    [TestNG] Time taken by org.testng.reporters.XMLReporter@ed3ef1: 16 ms
    [TestNG] Time taken by [FailedReporter passed=0 failed=0 skipped=0]: 15 ms
    [TestNG] Time taken by org.testng.reporters.jq.Main@d17bee: 63 ms
    [TestNG] Time taken by org.testng.reporters.EmailableReporter2@3534aa: 15 ms
    [TestNG] Time taken by org.testng.reporters.JUnitReportReporter@16432db: 16 ms
    

1 个答案:

答案 0 :(得分:1)

请在线查找我的答案:

1 - 显示下拉菜单列表,并且指定的选项也会突出显示,但单击/选择操作将被中止并选择默认值。

您先点击了下拉列表,然后尝试选择您不需要执行的项目。只需创建"Select class"对象并使用 selectByVisibleText("text to be selected") ,就可以完成下面所示的操作(只是摘自代码并根据需要进行修改

        we = driver.findElement(By.xpath(".//*[@id='cas7']"));
        se = new Select(we);
        se.selectByVisibleText(sh.getRow(2).getCell(5).getStringCellValue());

2 - 使用弹出窗口,selenium命令:&#34; driver.switchTo()。window(windowhandle)&#34;不管用。将打开新的弹出窗口并生成窗口句柄,但显示的错误为&#34;无法找到窗口{窗口句柄字符串}&#34;。

首先获取主窗口句柄,然后单击带来新窗口句柄的元素,并使用以下代码切换到新窗口(我刚刚修改了代码中的摘录

        String mainwindow = driver.getWindowHandle();        
        driver.findElement(By.xpath(".//*[@id='cas3_lkwgt']/img")).click();//Assuming clicking on this element brings out the new window

        Set<String> s = driver.getWindowHandles(); 
        Iterator<String> ite = s.iterator(); 
        while(ite.hasNext()) 
        { 
            String popup = ite.next(); 
            if(!popup.equalsIgnoreCase(mainwindow)){ 
                driver.switchTo().window(popup); 
                break;
              }
        }