【问题标题】:Selenium switching windows failure硒切换窗口失败
【发布时间】:2018-07-18 10:19:30
【问题描述】:

我正在使用 Selenium 编写一个需要多线程的网络爬虫

// selenium imports from org.openqa omitted
public class wpn
{
    private String sessionId = "";
    private String windowHandle = "";
    private WebDriver driver;

    public wpn (String id)
    {
        sessionId = id;
    }

    public void openDriver (String driverType)
    {
        if (driverType.equals ("ie"))
        {
            DesiredCapabilities capabilities = DesiredCapabilities.internetExplorer();
            capabilities.setCapability(InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS, true);
            capabilities.setCapability(InternetExplorerDriver.IE_ENSURE_CLEAN_SESSION, true);
            capabilities.setCapability("requireWindowFocus", true);
            System.setProperty("webdriver.ie.driver", "c:\\temp\\ieDriver.exe");
            driver = new InternetExplorerDriver(capabilities);
            driver.manage().window().maximize();
        }
        else if (driverType.equals ("chrome"))
        {
            DesiredCapabilities capabilities = DesiredCapabilities.chrome();
            capabilities.setCapability(CapabilityType.ForSeleniumServer.ENSURING_CLEAN_SESSION, true);
            System.setProperty("webdriver.chrome.driver", "c:\\temp\\chromedriver.exe");
            driver = new ChromeDriver (capabilities);
            driver.manage().window().maximize();
        }
        else if (driverType.equals ("phantom"))
        {
            File file = new File("c:\\temp\\phantomJSDdriver.exe");
            System.setProperty("phantomjs.binary.path", file.getAbsolutePath ());
            DesiredCapabilities capabilities = new DesiredCapabilities();
            capabilities.setJavascriptEnabled(true);
            capabilities.setCapability(PhantomJSDriverService.PHANTOMJS_CLI_ARGS, new String[] {"--web-security=no", "--ignore-ssl-errors=yes"});
            driver = new PhantomJSDriver(capabilities);
            Dimension dimension = new Dimension (1280, 1024);
            driver.manage().window().setSize (dimension);
        }
        else if (driverType.equals ("firefox"))
        {
            System.setProperty ("webdriver.gecko.driver", "c:\\temp\\geckodriver.exe");
            FirefoxOptions options = new FirefoxOptions ();
            options.setBinary (c:\\temp\\firefoxdriver.exe");
            options.addArguments("--headless");
            driver = new FirefoxDriver(options);
            driver.manage().window().maximize();
        }
        else
        {
            System.println("unrecognised driver type " + driverType); 
        }

        System.setProperty ("https.protocols", "TLSv1.2");
    }

    public void login (String loginUrl)
    {
        driver.get(loginUrl);
        windowHandle = driver.getWindowHandle ();
    }

    public void getInfo (String infoUrl)
    {
        try
        {
            String wh = driver.getWindowHandle ();
            if (!wh.matches(windowHandle))
            {
                driver.switchTo(windowHandle);
            }

            driver.get(infoUrl);
        }
        catch (Exception e)
        {
            System.out.println (e.getMessage ());
        }
    }
}

int main (String[] args)
{
    wpn session_1 = new wpn ("101");
    wpn session_2 = new wpn ("202");

    String driverType = args[0];
    session_1.openDriver (driverType);
    session_2.openDriver (driverType);

    session_1.login ("http://myService.com/login");
    session_2.login ("http://myService.com/login");

    session_2.info ("http://myService.com/info");
    // proceeds OK, because window handles match

    session_1.info ("http://myService.com/info");
    // produces failure when attempting to switch to session_1's window
}

使用 ie 驱动程序,错误类似于:

No window found  
Build info: version: '3.5.0', revision: '8def36e068', time: '2017-08-10T23:00:22.093Z'  
System info: host: 'HUWG', ip: '192.168.0.215', os.name: 'Windows 7', os.arch: 'amd64', os.version: '6.1', java.version: '1.8.0_144'  
Driver info: org.openqa.selenium.ie.InternetExplorerDriver  
Capabilities [{acceptInsecureCerts=false, browserVersion=11, se:ieOptions={nativeEvents=true, browserAttachTimeout=0.0, ie.ensureCleanSession=true, elementScrollBehavior=0.0, enablePersistentHover=false, ie.browserCommandLineSwitches=, ie.forceCreateProcessApi=false, requireWindowFocus=true, initialBrowserUrl=http://localhost:40976/, ignoreZoomSetting=false, ie.fileUploadDialogTimeout=3000.0, ignoreProtectedModeSettings=true}, browserName=internet explorer, pageLoadStrategy=normal, unhandledPromptBehavior=dismiss, javascriptEnabled=true, platformName=windows, setWindowRect=true, platform=ANY}]  
Session ID: cd72bba0-f105-43a8-a234-cbb494c19d8c  

Chrome 是这样的:

no such window  
  (Session info: chrome=67.0.3396.99)  
  (Driver info: chromedriver=2.40.565498  
 (ea082db3280dd6843ebfb08a625e3eb905c4f5ab),platform=Windows NT 6.1.7601 SP1 x86_64) (WARNING: The server did not provide any stacktrace information)  
Command duration or timeout: 0 milliseconds  
Build info: version: '3.13.0', revision: '2f0d292', time: '2018-06-25T15:32:19.891Z'  
System info: host: 'HUWG', ip: '192.168.0.215', os.name: 'Windows 7', os.arch: 'amd64', os.version: '6.1', java.version: '1.8.0_144'  
Driver info: org.openqa.selenium.chrome.ChromeDriver  
Capabilities {acceptInsecureCerts: false, acceptSslCerts: false, applicationCacheEnabled: false, browserConnectionEnabled: false, browserName: chrome, chrome: {chromedriverVersion: 2.40.565498 (ea082db3280dd6..., userDataDir: C:\Users\gallonh\AppData\Lo...}, cssSelectorsEnabled: true, databaseEnabled: false, handlesAlerts: true, hasTouchScreen: false, javascriptEnabled: true, locationContextEnabled: true, mobileEmulationEnabled: false, nativeEvents: true, networkConnectionEnabled: false, pageLoadStrategy: normal, platform: XP, platformName: XP, rotatable: false, setWindowRect: true, takesHeapSnapshot: true, takesScreenshot: true, unexpectedAlertBehaviour: , unhandledPromptBehavior: , version: 67.0.3396.99, webStorageEnabled: true}  
Session ID: c4c74d5258c723a0a09dbbf7284b1c48

使用 phantomJS 驱动,类似于:

no such window  
  (Session info: chrome=67.0.3396.99)  
  (Driver info: chromedriver=2.40.565498  
 (ea082db3280dd6843ebfb08a625e3eb905c4f5ab),platform=Windows NT 6.1.7601 SP1 x86_64) (WARNING: The server did not provide any stacktrace information)  
Command duration or timeout: 0 milliseconds  
Build info: version: '3.13.0', revision: '2f0d292', time: '2018-06-25T15:32:19.891Z'  
System info: host: 'HUWG', ip: '192.168.0.215', os.name: 'Windows 7', os.arch: 'amd64', os.version: '6.1', java.version: '1.8.0_144'  
Driver info: org.openqa.selenium.chrome.ChromeDriver  
Capabilities {acceptInsecureCerts: false, acceptSslCerts: false, applicationCacheEnabled: false, browserConnectionEnabled: false, browserName: chrome, chrome: {chromedriverVersion: 2.40.565498 (ea082db3280dd6..., userDataDir: C:\Users\gallonh\AppData\Lo...}, cssSelectorsEnabled: true, databaseEnabled: false, handlesAlerts: true, hasTouchScreen: false, javascriptEnabled: true, locationContextEnabled: true, mobileEmulationEnabled: false, nativeEvents: true, networkConnectionEnabled: false, pageLoadStrategy: normal, platform: XP, platformName: XP, rotatable: false, setWindowRect: true, takesHeapSnapshot: true, takesScreenshot: true, unexpectedAlertBehaviour: , unhandledPromptBehavior: , version: 67.0.3396.99, webStorageEnabled: true}  
Session ID: c4c74d5258c723a0a09dbbf7284b1c48

使用 Firefox 驱动程序,Selenium 打开的每个窗口的句柄都是“4294967297”,因此不会切换窗口。

对于 IE 和 phantomJS 驱动程序,我正在使用 selenium-server-standalone-3.5.0.jar 构建应用程序。对于 chrome 和 firefox 驱动程序,我正在使用 selenium-server-standalon-3.13.0.jar 构建应用程序。

【问题讨论】:

  • 请编辑问题以将其限制为具有足够详细信息的特定问题,以确定适当的答案。避免一次问多个不同的问题。请参阅How to Ask 页面以获得澄清此问题的帮助。

标签: java selenium selenium-webdriver selenium-chromedriver selenium-iedriver


【解决方案1】:

您使用的是正则表达式匹配器。 driver.getWindowHandle 返回一个字符串,你应该使用equals 来检查是否相等。此外,由于您没有在session.login(...)session.info(...) 之前切换窗口,因此检查驱动程序是否指向同一个窗口是多余的。

您已经初始化了两个独立的驱动程序实例,它们引用了它们自己的浏览器窗口。驱动它们自己的浏览器会话的驱动程序实例之间没有“串扰”。

如果您仍想检查是否仍指向同一个窗口,请使用wh.equals(windowHandle)

【讨论】:

    【解决方案2】:

    您使用以下 WebDrivervariants 提供了错误堆栈跟踪:

    • InternetExplorerDriver`
    • chromedriver=2.40
    • PhantomJSDriver

    首先值得一提的是,不同的浏览器客户端以不同的方式呈现HTML DOM。如果您可以将问题缩小到特定的 WebDriver/Browser Client 变体,那么调试问题可能会容易得多。

    分析所有三个错误跟踪日志块,似乎问题在于 切换窗口/选项卡,其中错误显示为:

    • No window foundInternetExplorerDriver
    • no such window (chromedriver=2.40)
    • no such window (PhantomJSDriver)

    但是,您的主要问题似乎是您使用的二进制文件版本之间的不兼容,如下所示:

    • 虽然您使用的是 selenium-server-standalone-3.5.0.jarselenium-server-standalon-3.13.0.jar 或者
    • 您的 JDK 版本似乎是 1.8.0_144,相当 > 和古代

    解决方案

    配置您的 Test Bed 以使用最新的 GA 二进制文件执行您的 Test Suite

    【讨论】: