Describes proxy settings to be used with a driver instance.
コード例 #1
0
        /// <summary>
        /// Performs the initialize of the browser.
        /// </summary>
        /// <param name="driverFolder">The driver folder.</param>
        /// <param name="proxy">The proxy.</param>
        /// <returns>
        /// The web driver.
        /// </returns>
        protected override IWebDriver PerformInitialize(string driverFolder, Proxy proxy)
        {
            var options = new PhantomJSOptions();
            options.AddAdditionalCapability(CapabilityType.Proxy, proxy);

            return new PhantomJSDriver(driverFolder, options);
        }
コード例 #2
0
        internal static void Main(string[] args)
        {
            // Note that we're using a port of 0, which tells Fiddler to
            // select a random available port to listen on.
            int proxyPort = StartFiddlerProxy(0);

            // We are only proxying HTTP traffic, but could just as easily
            // proxy HTTPS or FTP traffic.
            OpenQA.Selenium.Proxy proxy = new OpenQA.Selenium.Proxy();
            proxy.HttpProxy = string.Format("127.0.0.1:{0}", proxyPort);

            // See the code of the individual methods for the details of how
            // to create the driver instance with the proxy settings properly set.
            BrowserKind browser = BrowserKind.Chrome;
            //BrowserKind browser = BrowserKind.Firefox;
            //BrowserKind browser = BrowserKind.IE;
            //BrowserKind browser = BrowserKind.Edge;
            //BrowserKind browser = BrowserKind.PhantomJS;

            IWebDriver driver = WebDriverFactory.CreateWebDriverWithProxy(browser, proxy);

            TestStatusCodes(driver);

            driver.Quit();

            StopFiddlerProxy();
            Console.WriteLine("Complete! Press <Enter> to exit.");
            Console.ReadLine();
        }
コード例 #3
0
 /// <summary>
 /// Performs the initialize of the browser.
 /// </summary>
 /// <param name="driverFolder">The driver folder.</param>
 /// <param name="proxy">The proxy.</param>
 /// <returns>
 /// The web driver.
 /// </returns>
 protected override IWebDriver PerformInitialize(string driverFolder, Proxy proxy)
 {
     var options = new InternetExplorerOptions();
     options.Proxy = proxy;
     options.IntroduceInstabilityByIgnoringProtectedModeSettings = true;
     return new InternetExplorerDriver(driverFolder, options);
 }
コード例 #4
0
        internal static void Main(string[] args)
        {
            // Note that we're using a port of 0, which tells Fiddler to
            // select a random available port to listen on.
            int proxyPort = StartFiddlerProxy(0);

            // We are only proxying HTTP traffic, but could just as easily
            // proxy HTTPS or FTP traffic.
            OpenQA.Selenium.Proxy proxy = new OpenQA.Selenium.Proxy();
            proxy.HttpProxy = string.Format("127.0.0.1:{0}", proxyPort);

            // See the code of the individual methods for the details of how
            // to create the driver instance with the proxy settings properly set.
            IWebDriver driver = WebDriverFactory.CreateWebDriverWithProxy(BrowserKind.IE, proxy);
            ////IWebDriver driver = WebDriverFactory.CreateWebDriverWithProxy(BrowserKind.Firefox, proxy);
            ////IWebDriver driver = WebDriverFactory.CreateWebDriverWithProxy(BrowserKind.Chrome, proxy);
            ////IWebDriver driver = WebDriverFactory.CreateWebDriverWithProxy(BrowserKind.PhantomJS, proxy);

            TestJavaScriptErrors(driver);

            driver.Quit();

            StopFiddlerProxy();
            Console.WriteLine("Complete! Press <Enter> to exit.");
            Console.ReadLine();
        }
コード例 #5
0
ファイル: TestRunner.cs プロジェクト: ob1jedi/SeleniumProxy
        private void GetWebDriver(OpenQA.Selenium.Proxy seleniumProxy = null)
        {
            var options = new ChromeOptions {
                Proxy = seleniumProxy
            };

            _webDriver = new ChromeDriver(options);
        }
コード例 #6
0
        public static IWebDriver Create(BrowserConfiguration executionConfiguration)
        {
            ProcessCleanupService.KillAllDriversAndChildProcessesWindows();

            DisposeDriverService.TestRunStartTime = DateTime.Now;

            BrowserConfiguration = executionConfiguration;
            var wrappedWebDriver = default(IWebDriver);

            _proxyService = ServicesCollection.Current.Resolve <ProxyService>();
            var webDriverProxy = new OpenQA.Selenium.Proxy
            {
                HttpProxy = $"http://127.0.0.1:{_proxyService.Port}",
                SslProxy  = $"http://127.0.0.1:{_proxyService.Port}",
            };

            switch (executionConfiguration.ExecutionType)
            {
            case ExecutionType.Regular:
                wrappedWebDriver = InitializeDriverRegularMode(executionConfiguration, webDriverProxy);
                break;

            case ExecutionType.Grid:
                var gridUrl = ConfigurationService.GetSection <WebSettings>().ExecutionSettings.Url;
                if (gridUrl == null || !Uri.IsWellFormedUriString(gridUrl.ToString(), UriKind.Absolute))
                {
                    throw new ArgumentException("To execute your tests in WebDriver Grid mode you need to set the gridUri in the browserSettings file.");
                }

                DebuggerPort = GetFreeTcpPort();

                if (executionConfiguration.IsLighthouseEnabled && (executionConfiguration.BrowserType.Equals(BrowserType.Chrome) || executionConfiguration.BrowserType.Equals(BrowserType.ChromeHeadless)))
                {
                    executionConfiguration.DriverOptions.AddArgument("--remote-debugging-address=0.0.0.0");
                    executionConfiguration.DriverOptions.AddArgument($"--remote-debugging-port={DebuggerPort}");
                }

                Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
                wrappedWebDriver = new RemoteWebDriver(new Uri(gridUrl), executionConfiguration.DriverOptions);
                break;
            }

            var gridPageLoadTimeout = ConfigurationService.GetSection <WebSettings>().TimeoutSettings.PageLoadTimeout;

            wrappedWebDriver.Manage().Timeouts().PageLoad = TimeSpan.FromSeconds(gridPageLoadTimeout);
            var gridScriptTimeout = ConfigurationService.GetSection <WebSettings>().TimeoutSettings.ScriptTimeout;

            wrappedWebDriver.Manage().Timeouts().AsynchronousJavaScript = TimeSpan.FromSeconds(gridScriptTimeout);

            if (executionConfiguration.BrowserType != BrowserType.Edge)
            {
                FixDriverCommandExecutionDelay((WebDriver)wrappedWebDriver);
            }

            ChangeWindowSize(executionConfiguration.Size, wrappedWebDriver);

            return(wrappedWebDriver);
        }
コード例 #7
0
        /// <summary>
        /// Performs the initialize of the browser.
        /// </summary>
        /// <param name="driverFolder">The driver folder.</param>
        /// <param name="proxy">The proxy.</param>
        /// <returns>
        /// The web driver.
        /// </returns>
        protected override IWebDriver PerformInitialize(string driverFolder, Proxy proxy)
        {
            var options = new ChromeOptions();

            if (!string.IsNullOrWhiteSpace(proxy.HttpProxy))
            {
                options.AddAdditionalCapability(CapabilityType.Proxy, proxy);
            }

            return new ChromeDriver(driverFolder, options);
        }
コード例 #8
0
ファイル: TestRunner.cs プロジェクト: ob1jedi/SeleniumProxy
        private OpenQA.Selenium.Proxy AttachSeleniumToProxy()
        {
            var seleniumProxy = new OpenQA.Selenium.Proxy()
            {
                HttpProxy = _proxyHost,
                SslProxy  = _proxyHost,
                FtpProxy  = _proxyHost
            };

            return(seleniumProxy);
        }
コード例 #9
0
        public IWebDriver StartFirefoxBrowser()
        {
            var capabilities = new DesiredCapabilities();
            var proxy = new OpenQA.Selenium.Proxy();
            if (Config.Settings.httpProxy.useProxy)
            {
                proxy.HttpProxy = "localhost:" + TestBase.proxy.proxyPort;
                capabilities.SetCapability("proxy", proxy);
            }

            return new FirefoxDriver(capabilities);
        }
コード例 #10
0
        public void SetupProxy() {

            string PROXY = "localhost:8080";

            OpenQA.Selenium.Proxy proxy = new OpenQA.Selenium.Proxy();
            proxy.HttpProxy = PROXY;
            proxy.FtpProxy = PROXY;
            proxy.SslProxy = PROXY;
            DesiredCapabilities cap = new DesiredCapabilities();
            cap.SetCapability(CapabilityType.Proxy, proxy);

            IWebDriver driver = new FirefoxDriver(cap);
        }
コード例 #11
0
        public IWebDriver StartFirefoxBrowser()
        {
            var capabilities = new DesiredCapabilities();
            var proxy        = new OpenQA.Selenium.Proxy();

            if (Config.Settings.httpProxy.useProxy)
            {
                proxy.HttpProxy = "localhost:" + TestBase.proxy.proxyPort;
                capabilities.SetCapability("proxy", proxy);
            }

            return(new FirefoxDriver(capabilities));
        }
コード例 #12
0
        public void SetupProxy() {

            string PROXY = "localhost:8080";

            OpenQA.Selenium.Proxy proxy = new OpenQA.Selenium.Proxy();
            proxy.HttpProxy = PROXY;
            proxy.FtpProxy = PROXY;
            proxy.SslProxy = PROXY;
            DesiredCapabilities cap = DesiredCapabilities.InternetExplorer();
            cap.SetCapability(CapabilityType.Proxy, proxy);

            IWebDriver driver = new RemoteWebDriverDriver(new Uri("http://localhost:4444/wd/hub"), cap);
        }
コード例 #13
0
        public IWebDriver StartChromeBrowser()
        {
            var options = new ChromeOptions();

            // Add the WebDriver proxy capability.
            if (Config.Settings.httpProxy.useProxy)
            {
                var proxy = new OpenQA.Selenium.Proxy();
                proxy.HttpProxy = "localhost:" + TestBase.proxy.proxyPort;
                options.Proxy   = proxy;
            }

            return(new ChromeDriver(options));
        }
コード例 #14
0
        public IWebDriver StartSafariBrowser()
        {
            var options = new SafariOptions();

            // Add the WebDriver proxy capability.
            if (Config.Settings.httpProxy.startProxy)
            {
                var proxy = new OpenQA.Selenium.Proxy();
                proxy.HttpProxy = "localhost:" + TestBase.proxy.proxyPort;
                options.AddAdditionalCapability("proxy", proxy);
            }

            return(new SafariDriver(options));
        }
コード例 #15
0
        public void SetupProxy()
        {
            string PROXY = "localhost:8080";

            OpenQA.Selenium.Proxy proxy = new OpenQA.Selenium.Proxy();
            proxy.HttpProxy = PROXY;
            proxy.FtpProxy  = PROXY;
            proxy.SslProxy  = PROXY;
            DesiredCapabilities cap = new DesiredCapabilities();

            cap.SetCapability(CapabilityType.Proxy, proxy);

            IWebDriver driver = new FirefoxDriver(cap);
        }
コード例 #16
0
        public void SetupProxy()
        {
            string PROXY = "localhost:8080";

            OpenQA.Selenium.Proxy proxy = new OpenQA.Selenium.Proxy();
            proxy.HttpProxy = PROXY;
            proxy.FtpProxy  = PROXY;
            proxy.SslProxy  = PROXY;
            DesiredCapabilities cap = DesiredCapabilities.InternetExplorer();

            cap.SetCapability(CapabilityType.Proxy, proxy);

            IWebDriver driver = new RemoteWebDriverDriver(new Uri("http://localhost:4444/wd/hub"), cap);
        }
コード例 #17
0
        public IWebDriver StartPhantomJSBrowser()
        {
            var options = new PhantomJSOptions();

            if (Config.Settings.httpProxy.useProxy)
            {
                var proxy = new OpenQA.Selenium.Proxy();
                proxy.HttpProxy = Config.Settings.httpProxy.proxyUrl + ":" + TestBase.proxy.proxyPort;
                proxy.SslProxy  = Config.Settings.httpProxy.proxyUrl + ":" + TestBase.proxy.proxyPort;
                proxy.FtpProxy  = Config.Settings.httpProxy.proxyUrl + ":" + TestBase.proxy.proxyPort;
                options.AddAdditionalCapability("proxy", proxy);
            }

            return(new PhantomJSDriver(options));
        }
コード例 #18
0
        public IWebDriver Get()
        {
            OpenQA.Selenium.Proxy proxy = null;
            if (_configuration.WebDriver.UseFiddlerProxy)
            {
                proxy = base.GetProxy(_configuration);
            }

            var options = new OpenQA.Selenium.IE.InternetExplorerOptions();

            options.EnsureCleanSession = true;
            options.Proxy = proxy;

            return(new OpenQA.Selenium.IE.InternetExplorerDriver(options));
        }
        public void TestInitialize()
        {
            var proxy = new OpenQA.Selenium.Proxy
            {
                HttpProxy = "http://localhost:18882",
                SslProxy  = "http://localhost:18882",
                FtpProxy  = "http://localhost:18882"
            };
            var options = new ChromeOptions
            {
                Proxy = proxy
            };

            _driver = new ChromeDriver(Environment.CurrentDirectory, options);
        }
コード例 #20
0
        private void InitializeProxy()
        {
            Console.WriteLine("Initializing Proxy");

            FiddlerApplication.Startup(5000, true, false);
            FiddlerApplication.BeforeResponse += RequestCallback;

            // - Selenium Proxy
            Proxy = new Proxy
            {
                Kind         = ProxyKind.Manual,
                IsAutoDetect = false,
                HttpProxy    = "localhost:5000"
            };
        }
コード例 #21
0
        public IWebDriver StartIEBrowser()
        {
            var options = new InternetExplorerOptions();

            options.IntroduceInstabilityByIgnoringProtectedModeSettings = true;
            options.IgnoreZoomLevel = true;
            if (Config.Settings.httpProxy.startProxy)
            {
                var proxy = new OpenQA.Selenium.Proxy();
                proxy.HttpProxy            = "localhost:" + TestBase.proxy.proxyPort;
                options.Proxy              = proxy;
                options.UsePerProcessProxy = true;
            }

            return(new InternetExplorerDriver(options));
        }
コード例 #22
0
        /// <summary>
        /// Returns an instance of Firefox based driver.
        /// </summary>
        /// <returns>FireFox based driver</returns>
        private static IWebDriver FireFoxWebDriver()
        {
            // Proxy setup starts here
            OpenQA.Selenium.Proxy proxy = new OpenQA.Selenium.Proxy();

            //start fiddler and get the port used
            int proxyport = FiddlerProxy.StartFiddlerProxy(0);

            //use SslProxy for https sites
            proxy.SslProxy = string.Format("127.0.0.1:{0}", proxyport);


            FirefoxProfile profile = new FirefoxProfile();

            profile.AssumeUntrustedCertificateIssuer = false;
            // get Log Execution Path
            String getExecutingPath = new FileInfo(Assembly.GetExecutingAssembly().Location).DirectoryName;

            // set profile preferences
            profile.SetPreference("FireFox" + DateTime.Now.Ticks + ".log", getExecutingPath);
            profile.SetPreference("browser.helperApps.alwaysAsk.force", false);
            profile.SetPreference("browser.download.folderList", 2);
            profile.SetPreference("browser.download.dir", AutomationConfigurationManager.DownloadFilePath.Replace("file:\\", ""));
            profile.SetPreference("services.sync.prefs.sync.browser.download.manager.showWhenStarting", false);
            profile.SetPreference("browser.download.useDownloadDir", true);
            profile.SetPreference("browser.download.downloadDir", AutomationConfigurationManager.DownloadFilePath.Replace("file:\\", ""));
            profile.SetPreference("browser.download.defaultFolder", AutomationConfigurationManager.DownloadFilePath.Replace("file:\\", ""));
            profile.SetPreference("browser.helperApps.neverAsk.saveToDisk", "application/zip, application/x-zip, application/x-zip-compressed, application/download, application/octet-stream");
            profile.EnableNativeEvents = true;
            profile.SetPreference("browser.cache.disk.enable", false);
            profile.SetPreference("browser.cache.memory.enable", false);
            profile.SetPreference("browser.cache.offline.enable", false);
            profile.SetPreference("network.http.use-cache", false);
            //set proxyperference
            profile.SetProxyPreferences(proxy);
            //to be sure that it picks up 32bit of ff always
            string        sBrowserExe = "C:\\Program Files (x86)\\Mozilla Firefox\\firefox.exe";
            FirefoxBinary Bin         = new FirefoxBinary(sBrowserExe);
            IWebDriver    webDriver   = new FirefoxDriver();

            // set page load duration
            webDriver.Manage().Timeouts().SetPageLoadTimeout(TimeSpan.FromSeconds(TimeOut));
            // set cursor position center of the screen
            Cursor.Position = new Point(Screen.PrimaryScreen.Bounds.Width / 2, Screen.PrimaryScreen.Bounds.Height / 2);
            return(webDriver);
        }
コード例 #23
0
ファイル: InParser.cs プロジェクト: VodemSharp/TagSearcher
        public InParser(string id, string proxy_host, string proxy_port, QueryType queryType)
        {
            Id        = id;
            ProxyHost = proxy_host;
            ProxyPort = proxy_port;
            QueryType = queryType;

            Data = String.Format("{0}/{1}", ProxyHost, ProxyPort);

#pragma warning disable CS0618 // Type or member is obsolete

            PhantomJSDriverService service = PhantomJSDriverService.CreateDefaultService(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location));

            PhantomJSOptions options = null;

            if (ProxyHost != "0.0.0.0" && ProxyPort != "0")
            {
                OpenQA.Selenium.Proxy proxy = new OpenQA.Selenium.Proxy();
                proxy.HttpProxy = String.Format(ProxyHost + ":" + ProxyPort);
                proxy.Kind      = ProxyKind.Manual;

                service.ProxyType = "http";
                service.Proxy     = proxy.HttpProxy;

                options = new PhantomJSOptions {
                    Proxy = proxy
                };
            }

            service.HideCommandPromptWindow = true;
            service.IgnoreSslErrors         = true;
            service.SslProtocol             = "any";
            service.WebSecurity             = false;
            service.LocalToRemoteUrlAccess  = true;
            service.LoadImages = false;

            if (options == null)
            {
                Browser = new OpenQA.Selenium.PhantomJS.PhantomJSDriver(service);
            }
            else
            {
                Browser = new OpenQA.Selenium.PhantomJS.PhantomJSDriver(service, options);
            }
        }
コード例 #24
0
ファイル: ProxyTor.cs プロジェクト: lag21392/MultiTorProxy
        public static void EjecutarFirefoxProxy(string ipYPuerto)
        {
            try
            {
                FirefoxProfile        profile = new FirefoxProfile();
                String                PROXY   = ipYPuerto;
                OpenQA.Selenium.Proxy proxy   = new OpenQA.Selenium.Proxy();
                proxy.HttpProxy = PROXY;
                proxy.FtpProxy  = PROXY;
                proxy.SslProxy  = PROXY;
                profile.SetProxyPreferences(proxy);
                FirefoxOptions options = new FirefoxOptions();
                options.Profile = profile;
                options.AddArgument("https://www.cual-es-mi-ip.net");

                FirefoxDriver driver = new FirefoxDriver(options);
                driver.Close();
            }
            catch {
            }
        }
コード例 #25
0
        public IWebDriver Get()
        {
            OpenQA.Selenium.Proxy proxy = null;
            if (_configuration.WebDriver.UseFiddlerProxy)
            {
                proxy = base.GetProxy(_configuration);
            }

            var capabilities = _configuration.WebDriver.Driver.EqualsEx("firefox")
                ? DesiredCapabilities.Firefox()
                : DesiredCapabilities.Chrome();

            if (proxy != null)
            {
                capabilities.SetCapability(CapabilityType.Proxy, proxy);
            }

            if (_configuration.WebDriver.Driver.EqualsEx("firefox"))
            {
                return(new OpenQA.Selenium.Firefox.FirefoxDriver(capabilities));
            }
            return(new RemoteWebDriver(new Uri("http://localhost:9515"), capabilities));
        }
コード例 #26
0
ファイル: Driver.cs プロジェクト: apincik/InstaNet
        public void SetProxy(string ipAddress, string port, string username, string password)
        {
            //Proxy is not set for local loopback addresses
            if (String.IsNullOrEmpty(ipAddress) || ipAddress == "127.0.0.1" || ipAddress == "::1")
            {
                return;
            }

            OpenQA.Selenium.Proxy sProxy = new OpenQA.Selenium.Proxy();
            sProxy.Kind          = ProxyKind.Manual;
            sProxy.IsAutoDetect  = false;
            sProxy.HttpProxy     = ipAddress + ":" + port;
            sProxy.SslProxy      = ipAddress + ":" + port;
            sProxy.SocksUserName = username;
            sProxy.SocksPassword = username;
            _options.Proxy       = sProxy;

            //Workaround - submit login credentials dialog by loading custom extension. Does not work in icognito.
            ProxyExtension proxyExtension = new ProxyExtension();

            proxyExtension.SetConnectionDetails(ipAddress, port, username, password);
            AddExtension(proxyExtension);
        }
コード例 #27
0
        /// <summary>
        /// <see cref="IDriverBuilder.Build"/>.
        /// </summary>
        public IWebDriver Build()
        {
            var remoteAddress = new Uri(Configuration.ConfigurationReader.FrameworkConfig.GetRemoteServerByRole(role));
            var proxyAddress  = "";

            if (Browsers.Chrome.Equals(browser))
            {
                proxyAddress = Configuration.ConfigurationReader.FrameworkConfig.GetRemoteServerByRole(role);
            }
            if (Browsers.IExplorer.Equals(browser))
            {
                proxyAddress = Configuration.ConfigurationReader.FrameworkConfig.GetRemoteServerByRole(role);
            }
            if (proxyAddress != null && proxyAddress.Length > 0)
            {
                OpenQA.Selenium.Proxy proxy = new OpenQA.Selenium.Proxy();
                proxy.HttpProxy = proxyAddress;
                proxy.FtpProxy  = proxyAddress;
                proxy.SslProxy  = proxyAddress;
                desiredCapabilities.SetCapability("proxy", proxy);
            }
            return(new RemoteWebDriver(remoteAddress, desiredCapabilities));
        }
コード例 #28
0
ファイル: Program.cs プロジェクト: kmpangdudu/AutoBrowseWeb
        static void Main(string[] args)
        {
            int proxytime = Properties.Settings.Default.proxytime;
            int times     = Properties.Settings.Default.times;

            string web     = Properties.Settings.Default.page;
            string cate    = Properties.Settings.Default.cate;
            string proxies = Properties.Settings.Default.proxies;
            string psearch = Properties.Settings.Default.psearch;

            string[] allweb    = File.ReadAllLines(web);
            string[] allCate   = File.ReadAllLines(cate);
            string[] allproxy  = File.ReadAllLines(proxies);
            string[] allsearch = File.ReadAllLines(psearch);

            Random rnd1 = new Random();

            string thisPage   = "";
            string thisCate   = "";
            string thissearch = "";
            string PROXY      = "";


            //Code copied from the above linkss
            FirefoxProfile profile = new FirefoxProfile();
            FirefoxDriver  driver, driver0, driver2, driver1, driver3, driver5;

            OpenQA.Selenium.Proxy proxy = new OpenQA.Selenium.Proxy();

            FirefoxBinary binary = new FirefoxBinary(Properties.Settings.Default.Firefoxbin);
            //"C:\\Program Files (x86)\\Mozilla Firefox\\firefox.exe


            TimeSpan timespan = new TimeSpan();

            timespan = TimeSpan.FromMinutes(3);

            while (true)
            {
                Thread.Sleep(60 * proxytime * 1000);
                {
                    PROXY           = allproxy[rnd1.Next(allproxy.Length)];
                    proxy.HttpProxy = PROXY;
                    proxy.FtpProxy  = PROXY;
                    proxy.SslProxy  = PROXY;
                    profile.SetProxyPreferences(proxy);

                    //each proxy browe 3 categories and 2 webpages
                    // look at a category
                    {
                        //thisCate = allCate[rnd1.Next(allCate.Length)];
                        thisPage = allweb[rnd1.Next(allCate.Length)];
                        driver1  = new FirefoxDriver(profile);
                        driver1.Manage().Window.Size = new Size(300, 200);
                        driver1.Navigate().GoToUrl(thisCate);  //   Category 如果要扫目录就改成 thisCate
                        driver1.Close();
                    }

                    ///  search
                    Thread.Sleep(1000 * Properties.Settings.Default.Iterval1); // then look at a page
                    {
                        thissearch = allsearch[rnd1.Next(allsearch.Length)];
                        driver5    = new FirefoxDriver(profile);
                        driver5.Manage().Window.Size = new Size(300, 200);
                        driver5.Navigate().GoToUrl(thissearch); //   Search  如果要扫目录就改成 thisCate
                        driver5.Close();
                    }

                    Thread.Sleep(1000 * Properties.Settings.Default.Iterval1); // then look at a page
                    {
                        thisPage = allweb[rnd1.Next(allweb.Length)];
                        driver   = new FirefoxDriver(profile);
                        driver.Manage().Window.Size = new Size(300, 200);
                        driver.Navigate().GoToUrl(thisPage); //   Page 如果要扫目录就改成 thisCate
                        driver.Close();
                    }

                    Thread.Sleep(1000 * Properties.Settings.Default.Iterval2); // and then back to a category
                    {
                        thisCate = allCate[rnd1.Next(allCate.Length)];
                        //thisPage = allweb[rnd1.Next(allweb.Length)];
                        driver2 = new FirefoxDriver(profile);
                        driver2.Manage().Window.Size = new Size(300, 200);
                        driver2.Navigate().GoToUrl(thisCate);//   Category 如果要扫目录就改成 thisCate
                        driver2.Close();
                    }
                    Thread.Sleep(1000 * Properties.Settings.Default.Iterval3);// and then back to a category again
                    {
                        //thisCate = allCate[rnd1.Next(allCate.Length)];
                        thisPage = allweb[rnd1.Next(allweb.Length)];
                        driver3  = new FirefoxDriver(profile);
                        driver3.Manage().Window.Size = new Size(300, 200);
                        driver3.Navigate().GoToUrl(thisPage);//   Page 如果要扫目录就改成 thisCate
                        driver3.Close();
                    }

                    Thread.Sleep(1000 * Properties.Settings.Default.Iterval4); // finally look at one more page
                    {
                        thisPage = allweb[rnd1.Next(allweb.Length)];
                        driver0  = new FirefoxDriver(profile);
                        driver0.Manage().Window.Size = new Size(300, 200);
                        driver0.Navigate().GoToUrl(thisPage);//   Page 如果要扫目录就改成 thisCate
                        driver0.Close();
                    }
                };
            }
        }
コード例 #29
0
        private static IWebDriver InitializeDriverRegularMode(BrowserConfiguration executionConfiguration, OpenQA.Selenium.Proxy webDriverProxy)
        {
            IWebDriver wrappedWebDriver;

            switch (executionConfiguration.BrowserType)
            {
            case BrowserType.Chrome:
                new DriverManager().SetUpDriver(new ChromeConfig(), VersionResolveStrategy.MatchingBrowser);
                var chromeDriverService = ChromeDriverService.CreateDefaultService();
                chromeDriverService.SuppressInitialDiagnosticInformation = true;
                chromeDriverService.EnableVerboseLogging = false;
                var chromeOptions = executionConfiguration.DriverOptions;
                chromeOptions.AddArguments("--log-level=3");
                Port = GetFreeTcpPort();
                chromeDriverService.Port = Port;
                DebuggerPort             = GetFreeTcpPort();

                if (executionConfiguration.IsLighthouseEnabled)
                {
                    chromeOptions.AddArgument("--remote-debugging-address=0.0.0.0");
                    chromeOptions.AddArgument($"--remote-debugging-port={DebuggerPort}");
                    ////ProcessProvider.StartCLIProcess($"chrome-debug --port={Port}");
                    ////chromeOptions.DebuggerAddress = $"127.0.0.1:{Port}";
                }

                if (ConfigurationService.GetSection <WebSettings>().ExecutionSettings.PackedExtensionPath != null)
                {
                    string packedExtensionPath = ConfigurationService.GetSection <WebSettings>().ExecutionSettings.PackedExtensionPath.NormalizeAppPath();
                    Logger.LogInformation($"Trying to load packed extension from path: {packedExtensionPath}");
                    chromeOptions.AddExtension(ConfigurationService.GetSection <WebSettings>().ExecutionSettings.PackedExtensionPath);
                }

                if (ConfigurationService.GetSection <WebSettings>().ExecutionSettings.UnpackedExtensionPath != null)
                {
                    string unpackedExtensionPath = ConfigurationService.GetSection <WebSettings>().ExecutionSettings.UnpackedExtensionPath.NormalizeAppPath();
                    Logger.LogInformation($"Trying to load unpacked extension from path: {unpackedExtensionPath}");
                    chromeOptions.AddArguments($"load-extension={unpackedExtensionPath}");
                }

                if (executionConfiguration.ShouldCaptureHttpTraffic && _proxyService.IsEnabled && !executionConfiguration.IsLighthouseEnabled)
                {
                    chromeOptions.Proxy = webDriverProxy;
                }

                chromeOptions.AddArgument("hide-scrollbars");
                chromeOptions.SetLoggingPreference(LogType.Browser, LogLevel.All);
                chromeOptions.SetLoggingPreference("performance", LogLevel.All);

                wrappedWebDriver = new ChromeDriver(chromeDriverService, chromeOptions);
                break;

            case BrowserType.ChromeHeadless:
                new DriverManager().SetUpDriver(new ChromeConfig(), VersionResolveStrategy.MatchingBrowser);
                var chromeHeadlessDriverService = ChromeDriverService.CreateDefaultService();
                chromeHeadlessDriverService.SuppressInitialDiagnosticInformation = true;
                Port = GetFreeTcpPort();
                chromeHeadlessDriverService.Port = Port;
                var chromeHeadlessOptions = executionConfiguration.DriverOptions;
                chromeHeadlessOptions.AddArguments("--headless");
                chromeHeadlessOptions.AddArguments("--log-level=3");

                chromeHeadlessOptions.AddArguments("--test-type");
                chromeHeadlessOptions.AddArguments("--disable-infobars");
                chromeHeadlessOptions.AddArguments("--allow-no-sandbox-job");
                chromeHeadlessOptions.AddArguments("--ignore-certificate-errors");
                chromeHeadlessOptions.AddArguments("--disable-gpu");
                chromeHeadlessOptions.AddArguments("--no-sandbox");
                chromeHeadlessOptions.AddUserProfilePreference("credentials_enable_service", false);
                chromeHeadlessOptions.AddUserProfilePreference("profile.password_manager_enabled", false);
                chromeHeadlessOptions.AddArgument("hide-scrollbars");
                chromeHeadlessOptions.UnhandledPromptBehavior = UnhandledPromptBehavior.Dismiss;

                Port = GetFreeTcpPort();
                chromeHeadlessDriverService.Port = Port;
                DebuggerPort = GetFreeTcpPort();

                if (executionConfiguration.IsLighthouseEnabled)
                {
                    chromeHeadlessOptions.AddArgument("--remote-debugging-address=0.0.0.0");
                    chromeHeadlessOptions.AddArgument($"--remote-debugging-port={DebuggerPort}");
                }

                if (ConfigurationService.GetSection <WebSettings>().ExecutionSettings.PackedExtensionPath != null)
                {
                    string packedExtensionPath = ConfigurationService.GetSection <WebSettings>().ExecutionSettings.PackedExtensionPath.NormalizeAppPath();
                    Logger.LogInformation($"Trying to load packed extension from path: {packedExtensionPath}");
                    chromeHeadlessOptions.AddExtension(ConfigurationService.GetSection <WebSettings>().ExecutionSettings.PackedExtensionPath);
                }

                if (ConfigurationService.GetSection <WebSettings>().ExecutionSettings.UnpackedExtensionPath != null)
                {
                    string unpackedExtensionPath = ConfigurationService.GetSection <WebSettings>().ExecutionSettings.UnpackedExtensionPath.NormalizeAppPath();
                    Logger.LogInformation($"Trying to load unpacked extension from path: {unpackedExtensionPath}");
                    chromeHeadlessOptions.AddArguments($"load-extension={unpackedExtensionPath}");
                }

                if (executionConfiguration.ShouldCaptureHttpTraffic && _proxyService.IsEnabled)
                {
                    chromeHeadlessOptions.Proxy = webDriverProxy;
                }

                chromeHeadlessOptions.SetLoggingPreference(LogType.Browser, LogLevel.All);
                chromeHeadlessOptions.SetLoggingPreference("performance", LogLevel.All);

                wrappedWebDriver = new ChromeDriver(chromeHeadlessDriverService, chromeHeadlessOptions);
                break;

            case BrowserType.Firefox:
                new DriverManager().SetUpDriver(new FirefoxConfig(), VersionResolveStrategy.Latest);
                Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
                var firefoxOptions = executionConfiguration.DriverOptions;
                firefoxOptions.AddAdditionalOption("acceptInsecureCerts", true);
                if (executionConfiguration.ShouldCaptureHttpTraffic && _proxyService.IsEnabled)
                {
                    firefoxOptions.Proxy = webDriverProxy;
                }

                var firefoxService = FirefoxDriverService.CreateDefaultService();
                firefoxService.SuppressInitialDiagnosticInformation = true;
                firefoxService.Port = GetFreeTcpPort();
                if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                {
                    if (File.Exists(@"C:\Program Files\Mozilla Firefox\firefox.exe"))
                    {
                        firefoxService.FirefoxBinaryPath = @"C:\Program Files\Mozilla Firefox\firefox.exe";
                    }
                    else
                    {
                        firefoxService.FirefoxBinaryPath = @"C:\Program Files (x86)\Mozilla Firefox\firefox.exe";
                    }

                    // TODO: Anton(15.12.2019): Add option to set the path via environment variable.
                }

                var firefoxProfile = ServicesCollection.Current.Resolve <FirefoxProfile>(executionConfiguration.ClassFullName);
                if (firefoxProfile == null)
                {
                    firefoxOptions.Profile = new FirefoxProfile(_driverExecutablePath);
                    ServicesCollection.Current.RegisterInstance(firefoxOptions.Profile, executionConfiguration.ClassFullName);
                }

                if (ConfigurationService.GetSection <WebSettings>().ExecutionSettings.PackedExtensionPath != null)
                {
                    Logger.LogError($"Packed Extension loading not supported in Firefox!");

                    // 05-Nov-2020 navramov: Extension loading does not work
                    ////string packedExtensionPath = ConfigurationService.GetSection<WebSettings>().Firefox.PackedExtensionPath.NormalizeAppPath();
                    ////Logger.LogInformation($"Trying to load packed extension from path: {packedExtensionPath}");
                    ////firefoxOptions.Profile.AddExtension(ConfigurationService.GetSection<WebSettings>().Firefox.PackedExtensionPath);
                }

                if (ConfigurationService.GetSection <WebSettings>().ExecutionSettings.UnpackedExtensionPath != null)
                {
                    Logger.LogError($"Unpacked Extension loading not supported in Firefox!");
                }

                var firefoxTimeout = TimeSpan.FromSeconds(180);
                wrappedWebDriver = new FirefoxDriver(firefoxService, firefoxOptions, firefoxTimeout);
                break;

            case BrowserType.FirefoxHeadless:
                new DriverManager().SetUpDriver(new FirefoxConfig());
                var firefoxHeadlessOptions = executionConfiguration.DriverOptions;
                firefoxHeadlessOptions.AddArguments("--headless");
                firefoxHeadlessOptions.AddAdditionalOption("acceptInsecureCerts", true);
                if (executionConfiguration.ShouldCaptureHttpTraffic && _proxyService.IsEnabled)
                {
                    firefoxHeadlessOptions.Proxy = webDriverProxy;
                }

                if (ConfigurationService.GetSection <WebSettings>().ExecutionSettings.PackedExtensionPath != null)
                {
                    string packedExtensionPath = ConfigurationService.GetSection <WebSettings>().ExecutionSettings.PackedExtensionPath.NormalizeAppPath();
                    Logger.LogInformation($"Trying to load packed extension from path: {packedExtensionPath}");
                    firefoxHeadlessOptions.Profile.AddExtension(ConfigurationService.GetSection <WebSettings>().ExecutionSettings.PackedExtensionPath);
                }

                if (ConfigurationService.GetSection <WebSettings>().ExecutionSettings.UnpackedExtensionPath != null)
                {
                    Logger.LogError($"Unpacked Extension loading not supported in Firefox!");
                }

                var service = FirefoxDriverService.CreateDefaultService();
                service.SuppressInitialDiagnosticInformation = true;
                if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                {
                    if (File.Exists(@"C:\Program Files\Mozilla Firefox\firefox.exe"))
                    {
                        service.FirefoxBinaryPath = @"C:\Program Files\Mozilla Firefox\firefox.exe";
                    }
                    else
                    {
                        service.FirefoxBinaryPath = @"C:\Program Files (x86)\Mozilla Firefox\firefox.exe";
                    }

                    // TODO: Anton(15.12.2019): Add option to set the path via environment variable.
                }

                service.Port     = GetFreeTcpPort();
                wrappedWebDriver = new FirefoxDriver(service, firefoxHeadlessOptions);
                break;

            case BrowserType.Edge:
                new DriverManager().SetUpDriver(new EdgeConfig());
                var edgeDriverService = Microsoft.Edge.SeleniumTools.EdgeDriverService.CreateChromiumService();
                edgeDriverService.SuppressInitialDiagnosticInformation = true;
                var edgeOptions = executionConfiguration.DriverOptions;
                edgeOptions.PageLoadStrategy = PageLoadStrategy.Normal;
                edgeOptions.UseChromium      = true;
                edgeOptions.AddArguments("--log-level=3");
                if (executionConfiguration.ShouldCaptureHttpTraffic && _proxyService.IsEnabled)
                {
                    edgeOptions.Proxy = webDriverProxy;
                }

                if (ConfigurationService.GetSection <WebSettings>().ExecutionSettings.PackedExtensionPath != null)
                {
                    string packedExtensionPath = ConfigurationService.GetSection <WebSettings>().ExecutionSettings.PackedExtensionPath.NormalizeAppPath();
                    Logger.LogInformation($"Trying to load packed extension from path: {packedExtensionPath}");
                    edgeOptions.AddExtension(ConfigurationService.GetSection <WebSettings>().ExecutionSettings.PackedExtensionPath);
                }

                if (ConfigurationService.GetSection <WebSettings>().ExecutionSettings.UnpackedExtensionPath != null)
                {
                    string unpackedExtensionPath = ConfigurationService.GetSection <WebSettings>().ExecutionSettings.UnpackedExtensionPath.NormalizeAppPath();
                    Logger.LogInformation($"Trying to load unpacked extension from path: {unpackedExtensionPath}");
                    edgeOptions.AddArguments($"load-extension={unpackedExtensionPath}");
                }

                edgeOptions.SetLoggingPreference(LogType.Browser, LogLevel.Severe);
                edgeOptions.SetLoggingPreference("performance", LogLevel.All);


                wrappedWebDriver = new Microsoft.Edge.SeleniumTools.EdgeDriver(edgeDriverService, edgeOptions);
                break;

            case BrowserType.EdgeHeadless:
                new DriverManager().SetUpDriver(new EdgeConfig());
                var edgeHeadlessDriverService = Microsoft.Edge.SeleniumTools.EdgeDriverService.CreateChromiumService();
                edgeHeadlessDriverService.SuppressInitialDiagnosticInformation = true;
                var edgeHeadlessOptions = executionConfiguration.DriverOptions;
                edgeHeadlessOptions.AddArguments("--headless");
                edgeHeadlessOptions.AddArguments("--log-level=3");

                edgeHeadlessOptions.AddArguments("--test-type");
                edgeHeadlessOptions.AddArguments("--disable-infobars");
                edgeHeadlessOptions.AddArguments("--allow-no-sandbox-job");
                edgeHeadlessOptions.AddArguments("--ignore-certificate-errors");
                edgeHeadlessOptions.AddArguments("--disable-gpu");
                edgeHeadlessOptions.AddArguments("--no-sandbox");
                edgeHeadlessOptions.AddUserProfilePreference("credentials_enable_service", false);
                edgeHeadlessOptions.AddUserProfilePreference("profile.password_manager_enabled", false);
                edgeHeadlessOptions.AddArgument("hide-scrollbars");
                edgeHeadlessOptions.UnhandledPromptBehavior = UnhandledPromptBehavior.Dismiss;

                edgeHeadlessOptions.PageLoadStrategy = PageLoadStrategy.Normal;
                edgeHeadlessOptions.UseChromium      = true;
                if (executionConfiguration.ShouldCaptureHttpTraffic && _proxyService.IsEnabled)
                {
                    edgeHeadlessOptions.Proxy = webDriverProxy;
                }

                if (ConfigurationService.GetSection <WebSettings>().ExecutionSettings.PackedExtensionPath != null)
                {
                    string packedExtensionPath = ConfigurationService.GetSection <WebSettings>().ExecutionSettings.PackedExtensionPath.NormalizeAppPath();
                    Logger.LogInformation($"Trying to load packed extension from path: {packedExtensionPath}");
                    edgeHeadlessOptions.AddExtension(ConfigurationService.GetSection <WebSettings>().ExecutionSettings.PackedExtensionPath);
                }

                if (ConfigurationService.GetSection <WebSettings>().ExecutionSettings.UnpackedExtensionPath != null)
                {
                    string unpackedExtensionPath = ConfigurationService.GetSection <WebSettings>().ExecutionSettings.UnpackedExtensionPath.NormalizeAppPath();
                    Logger.LogInformation($"Trying to load unpacked extension from path: {unpackedExtensionPath}");
                    edgeHeadlessOptions.AddExtensionPath(unpackedExtensionPath);
                }

                edgeHeadlessOptions.SetLoggingPreference(LogType.Browser, LogLevel.Severe);
                edgeHeadlessOptions.SetLoggingPreference("performance", LogLevel.All);

                wrappedWebDriver = new Microsoft.Edge.SeleniumTools.EdgeDriver(edgeHeadlessDriverService, edgeHeadlessOptions);
                break;

            case BrowserType.Opera:
                new DriverManager().SetUpDriver(new OperaConfig());

                // the driver will be different for different OS.
                // Check for different releases- https://github.com/operasoftware/operachromiumdriver/releases
                var operaOptions = executionConfiguration.DriverOptions;

                if (executionConfiguration.ShouldCaptureHttpTraffic && _proxyService.IsEnabled)
                {
                    operaOptions.Proxy = webDriverProxy;
                }

                var operaService = OperaDriverService.CreateDefaultService();
                operaService.SuppressInitialDiagnosticInformation = true;
                operaService.Port = GetFreeTcpPort();

                try
                {
                    wrappedWebDriver = new OperaDriver(operaService, operaOptions);
                }
                catch (WebDriverException ex) when(ex.Message.Contains("DevToolsActivePort file doesn't exist"))
                {
                    throw new Exception("This is a known issue in the latest versions of Opera driver. It is reported to the Opera team. As soon it is fixed we will update BELLATRIX.", ex);
                }

                break;

            case BrowserType.InternetExplorer:
                new DriverManager().SetUpDriver(new InternetExplorerConfig());

                // Steps to configure IE to always allow blocked content:
                // From Internet Explorer, select the Tools menu, then the Options...
                // In the Internet Options dialog, select the Advanced tab...
                // Scroll down until you see the Security options. Enable the checkbox "Allow active content to run in files on My Computer"
                // Also, check https://github.com/SeleniumHQ/selenium/wiki/InternetExplorerDriver#required-configuration
                // in case of OpenQA.Selenium.NoSuchWindowException: Unable to get browser --> Uncheck IE Options --> Security Tab -> Uncheck "Enable Protected Mode"
                var ieOptions = executionConfiguration.DriverOptions;
                ieOptions.IntroduceInstabilityByIgnoringProtectedModeSettings = true;
                ieOptions.IgnoreZoomLevel      = true;
                ieOptions.EnableNativeEvents   = false;
                ieOptions.EnsureCleanSession   = true;
                ieOptions.PageLoadStrategy     = PageLoadStrategy.Eager;
                ieOptions.ForceShellWindowsApi = true;
                ieOptions.AddAdditionalCapability("disable-popup-blocking", true);

                if (executionConfiguration.ShouldCaptureHttpTraffic && _proxyService.IsEnabled)
                {
                    ieOptions.Proxy = webDriverProxy;
                }

                wrappedWebDriver = new InternetExplorerDriver(_driverExecutablePath, ieOptions);
                break;

            case BrowserType.Safari:
                var safariOptions = executionConfiguration.DriverOptions;

                if (executionConfiguration.ShouldCaptureHttpTraffic && _proxyService.IsEnabled)
                {
                    safariOptions.Proxy = webDriverProxy;
                }

                wrappedWebDriver = new SafariDriver(safariOptions);
                break;

            default:
                throw new NotSupportedException($"Not supported browser {executionConfiguration.BrowserType}");
            }

            return(wrappedWebDriver);
        }
コード例 #30
0
        private static IWebDriver InitializeDriverRegularMode(BrowserConfiguration executionConfiguration, OpenQA.Selenium.Proxy webDriverProxy)
        {
            IWebDriver wrappedWebDriver;

            switch (executionConfiguration.BrowserType)
            {
            case BrowserType.Chrome:
                new DriverManager().SetUpDriver(new ChromeConfig());
                var chromeDriverService = ChromeDriverService.CreateDefaultService(_driverExecutablePath);
                chromeDriverService.SuppressInitialDiagnosticInformation = true;
                chromeDriverService.EnableVerboseLogging = false;
                chromeDriverService.Port = GetFreeTcpPort();
                var chromeOptions = GetChromeOptions(executionConfiguration.ClassFullName);
                chromeOptions.AddArguments("--log-level=3");
                if (executionConfiguration.ShouldCaptureHttpTraffic && _proxyService.IsEnabled)
                {
                    chromeOptions.Proxy = webDriverProxy;
                }

                wrappedWebDriver = new ChromeDriver(chromeDriverService, chromeOptions);
                var chromePageLoadTimeout = ConfigurationService.GetSection <WebSettings>().Chrome.PageLoadTimeout;
                wrappedWebDriver.Manage().Timeouts().PageLoad = TimeSpan.FromSeconds(chromePageLoadTimeout);
                var chromeScriptTimeout = ConfigurationService.GetSection <WebSettings>().Chrome.ScriptTimeout;
                wrappedWebDriver.Manage().Timeouts().AsynchronousJavaScript = TimeSpan.FromSeconds(chromeScriptTimeout);
                BrowserSettings = ConfigurationService.GetSection <WebSettings>().Chrome;
                break;

            case BrowserType.ChromeHeadless:
                new DriverManager().SetUpDriver(new ChromeConfig());
                var chromeHeadlessDriverService = ChromeDriverService.CreateDefaultService(_driverExecutablePath);
                chromeHeadlessDriverService.SuppressInitialDiagnosticInformation = true;
                chromeHeadlessDriverService.Port = GetFreeTcpPort();
                var chromeHeadlessOptions = GetChromeOptions(executionConfiguration.ClassFullName);
                chromeHeadlessOptions.AddArguments("--headless");
                chromeHeadlessOptions.AddArguments("--log-level=3");
                if (executionConfiguration.ShouldCaptureHttpTraffic && _proxyService.IsEnabled)
                {
                    chromeHeadlessOptions.Proxy = webDriverProxy;
                }

                wrappedWebDriver = new ChromeDriver(chromeHeadlessDriverService, chromeHeadlessOptions);
                var chromeHeadlessPageLoadTimeout             = ConfigurationService.GetSection <WebSettings>().ChromeHeadless.PageLoadTimeout;
                wrappedWebDriver.Manage().Timeouts().PageLoad = TimeSpan.FromSeconds(chromeHeadlessPageLoadTimeout);
                var chromeHeadlessScriptTimeout = ConfigurationService.GetSection <WebSettings>().ChromeHeadless.ScriptTimeout;
                wrappedWebDriver.Manage().Timeouts().AsynchronousJavaScript = TimeSpan.FromSeconds(chromeHeadlessScriptTimeout);
                BrowserSettings = ConfigurationService.GetSection <WebSettings>().ChromeHeadless;
                break;

            case BrowserType.Firefox:
                new DriverManager().SetUpDriver(new FirefoxConfig());
                Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
                var firefoxOptions = GetFirefoxOptions(executionConfiguration.ClassFullName);
                if (executionConfiguration.ShouldCaptureHttpTraffic && _proxyService.IsEnabled)
                {
                    firefoxOptions.Proxy = webDriverProxy;
                }

                var firefoxService = FirefoxDriverService.CreateDefaultService(_driverExecutablePath);
                firefoxService.SuppressInitialDiagnosticInformation = true;
                firefoxService.Port = GetFreeTcpPort();
                if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                {
                    if (File.Exists(@"C:\Program Files\Mozilla Firefox\firefox.exe"))
                    {
                        firefoxService.FirefoxBinaryPath = @"C:\Program Files\Mozilla Firefox\firefox.exe";
                    }
                    else
                    {
                        firefoxService.FirefoxBinaryPath = @"C:\Program Files (x86)\Mozilla Firefox\firefox.exe";
                    }

                    // TODO: Anton(15.12.2019): Add option to set the path via environment variable.
                }

                var firefoxProfile = ServicesCollection.Current.Resolve <FirefoxProfile>(executionConfiguration.ClassFullName);
                if (firefoxProfile != null)
                {
                    firefoxOptions.Profile = firefoxProfile;
                }

                var firefoxTimeout = TimeSpan.FromSeconds(180);
                wrappedWebDriver = new FirefoxDriver(firefoxService, firefoxOptions, firefoxTimeout);
                var firefoxPageLoadTimeout = ConfigurationService.GetSection <WebSettings>().Firefox.PageLoadTimeout;
                wrappedWebDriver.Manage().Timeouts().PageLoad = TimeSpan.FromSeconds(firefoxPageLoadTimeout);
                var firefoxScriptTimeout = ConfigurationService.GetSection <WebSettings>().Firefox.ScriptTimeout;
                wrappedWebDriver.Manage().Timeouts().AsynchronousJavaScript = TimeSpan.FromSeconds(firefoxScriptTimeout);
                BrowserSettings = ConfigurationService.GetSection <WebSettings>().Firefox;
                break;

            case BrowserType.FirefoxHeadless:
                new DriverManager().SetUpDriver(new FirefoxConfig());
                var firefoxHeadlessOptions = GetFirefoxOptions(executionConfiguration.ClassFullName);
                firefoxHeadlessOptions.AddArguments("--headless");
                if (executionConfiguration.ShouldCaptureHttpTraffic && _proxyService.IsEnabled)
                {
                    firefoxHeadlessOptions.Proxy = webDriverProxy;
                }

                var service = FirefoxDriverService.CreateDefaultService(_driverExecutablePath);
                service.SuppressInitialDiagnosticInformation = true;
                if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                {
                    if (File.Exists(@"C:\Program Files\Mozilla Firefox\firefox.exe"))
                    {
                        service.FirefoxBinaryPath = @"C:\Program Files\Mozilla Firefox\firefox.exe";
                    }
                    else
                    {
                        service.FirefoxBinaryPath = @"C:\Program Files (x86)\Mozilla Firefox\firefox.exe";
                    }

                    // TODO: Anton(15.12.2019): Add option to set the path via environment variable.
                }

                service.Port     = GetFreeTcpPort();
                wrappedWebDriver = new FirefoxDriver(service, firefoxHeadlessOptions);
                var firefoxHeadlessPageLoadTimeout            = ConfigurationService.GetSection <WebSettings>().FirefoxHeadless.PageLoadTimeout;
                wrappedWebDriver.Manage().Timeouts().PageLoad = TimeSpan.FromSeconds(firefoxHeadlessPageLoadTimeout);
                var firefoxHeadlessScriptTimeout = ConfigurationService.GetSection <WebSettings>().FirefoxHeadless.ScriptTimeout;
                wrappedWebDriver.Manage().Timeouts().AsynchronousJavaScript = TimeSpan.FromSeconds(firefoxHeadlessScriptTimeout);
                BrowserSettings = ConfigurationService.GetSection <WebSettings>().FirefoxHeadless;
                break;

            case BrowserType.Edge:
                new DriverManager().SetUpDriver(new EdgeConfig());
                var edgeDriverService = Microsoft.Edge.SeleniumTools.EdgeDriverService.CreateChromiumService(_driverExecutablePath);
                edgeDriverService.SuppressInitialDiagnosticInformation = true;
                var edgeOptions = GetEdgeOptions(executionConfiguration.ClassFullName);
                edgeOptions.PageLoadStrategy = PageLoadStrategy.Normal;
                edgeOptions.UseChromium      = true;
                edgeOptions.AddArguments("--log-level=3");
                if (executionConfiguration.ShouldCaptureHttpTraffic && _proxyService.IsEnabled)
                {
                    edgeOptions.Proxy = webDriverProxy;
                }

                wrappedWebDriver = new Microsoft.Edge.SeleniumTools.EdgeDriver(edgeDriverService, edgeOptions);
                var edgePageLoadTimeout = ConfigurationService.GetSection <WebSettings>().Edge.PageLoadTimeout;
                wrappedWebDriver.Manage().Timeouts().PageLoad = TimeSpan.FromSeconds(edgePageLoadTimeout);
                var edgeScriptTimeout = ConfigurationService.GetSection <WebSettings>().Edge.ScriptTimeout;
                wrappedWebDriver.Manage().Timeouts().AsynchronousJavaScript = TimeSpan.FromSeconds(edgeScriptTimeout);
                BrowserSettings = ConfigurationService.GetSection <WebSettings>().Edge;
                break;

            case BrowserType.EdgeHeadless:
                new DriverManager().SetUpDriver(new EdgeConfig());
                var edgeHeadlessDriverService = Microsoft.Edge.SeleniumTools.EdgeDriverService.CreateChromiumService(_driverExecutablePath);
                edgeHeadlessDriverService.SuppressInitialDiagnosticInformation = true;
                var edgeHeadlessOptions = GetEdgeOptions(executionConfiguration.ClassFullName);
                edgeHeadlessOptions.AddArguments("--headless");
                edgeHeadlessOptions.AddArguments("--log-level=3");
                edgeHeadlessOptions.PageLoadStrategy = PageLoadStrategy.Normal;
                edgeHeadlessOptions.UseChromium      = true;
                if (executionConfiguration.ShouldCaptureHttpTraffic && _proxyService.IsEnabled)
                {
                    edgeHeadlessOptions.Proxy = webDriverProxy;
                }

                wrappedWebDriver = new Microsoft.Edge.SeleniumTools.EdgeDriver(edgeHeadlessDriverService, edgeHeadlessOptions);
                var edgeHeadlessPageLoadTimeout = ConfigurationService.GetSection <WebSettings>().Edge.PageLoadTimeout;
                wrappedWebDriver.Manage().Timeouts().PageLoad = TimeSpan.FromSeconds(edgeHeadlessPageLoadTimeout);
                var edgeHeadlessScriptTimeout = ConfigurationService.GetSection <WebSettings>().Edge.ScriptTimeout;
                wrappedWebDriver.Manage().Timeouts().AsynchronousJavaScript = TimeSpan.FromSeconds(edgeHeadlessScriptTimeout);
                BrowserSettings = ConfigurationService.GetSection <WebSettings>().Edge;
                break;

            case BrowserType.Opera:
                new DriverManager().SetUpDriver(new OperaConfig());

                // the driver will be different for different OS.
                // Check for different releases- https://github.com/operasoftware/operachromiumdriver/releases
                var operaOptions = GetOperaOptions(executionConfiguration.ClassFullName);

                if (executionConfiguration.ShouldCaptureHttpTraffic && _proxyService.IsEnabled)
                {
                    operaOptions.Proxy = webDriverProxy;
                }

                var operaService = OperaDriverService.CreateDefaultService(_driverExecutablePath);
                operaService.SuppressInitialDiagnosticInformation = true;
                operaService.Port = GetFreeTcpPort();

                try
                {
                    wrappedWebDriver = new OperaDriver(operaService, operaOptions);
                }
                catch (WebDriverException ex) when(ex.Message.Contains("DevToolsActivePort file doesn't exist"))
                {
                    throw new Exception("This is a known issue in the latest versions of Opera driver. It is reported to the Opera team. As soon it is fixed we will update BELLATRIX.", ex);
                }

                var operaPageLoadTimeout = ConfigurationService.GetSection <WebSettings>().Opera.PageLoadTimeout;
                wrappedWebDriver.Manage().Timeouts().PageLoad = TimeSpan.FromSeconds(operaPageLoadTimeout);
                var operaScriptTimeout = ConfigurationService.GetSection <WebSettings>().Opera.ScriptTimeout;
                wrappedWebDriver.Manage().Timeouts().AsynchronousJavaScript = TimeSpan.FromSeconds(operaScriptTimeout);
                BrowserSettings = ConfigurationService.GetSection <WebSettings>().Opera;
                break;

            case BrowserType.InternetExplorer:
                new DriverManager().SetUpDriver(new InternetExplorerConfig());

                // Steps to configure IE to always allow blocked content:
                // From Internet Explorer, select the Tools menu, then the Options...
                // In the Internet Options dialog, select the Advanced tab...
                // Scroll down until you see the Security options. Enable the checkbox "Allow active content to run in files on My Computer"
                // Also, check https://github.com/SeleniumHQ/selenium/wiki/InternetExplorerDriver#required-configuration
                // in case of OpenQA.Selenium.NoSuchWindowException: Unable to get browser --> Uncheck IE Options --> Security Tab -> Uncheck "Enable Protected Mode"
                var ieOptions = GetInternetExplorerOptions(executionConfiguration.ClassFullName);
                ieOptions.IntroduceInstabilityByIgnoringProtectedModeSettings = true;
                ieOptions.IgnoreZoomLevel      = true;
                ieOptions.EnableNativeEvents   = false;
                ieOptions.EnsureCleanSession   = true;
                ieOptions.PageLoadStrategy     = PageLoadStrategy.Eager;
                ieOptions.ForceShellWindowsApi = true;
                ieOptions.AddAdditionalCapability("disable-popup-blocking", true);

                if (executionConfiguration.ShouldCaptureHttpTraffic && _proxyService.IsEnabled)
                {
                    ieOptions.Proxy = webDriverProxy;
                }

                wrappedWebDriver = new InternetExplorerDriver(_driverExecutablePath, ieOptions);

                var iePageLoadTimeout = ConfigurationService.GetSection <WebSettings>().InternetExplorer.PageLoadTimeout;
                wrappedWebDriver.Manage().Timeouts().PageLoad = TimeSpan.FromSeconds(iePageLoadTimeout);
                var ieScriptTimeout = ConfigurationService.GetSection <WebSettings>().InternetExplorer.ScriptTimeout;
                wrappedWebDriver.Manage().Timeouts().AsynchronousJavaScript = TimeSpan.FromSeconds(ieScriptTimeout);
                BrowserSettings = ConfigurationService.GetSection <WebSettings>().InternetExplorer;
                break;

            case BrowserType.Safari:
                var safariOptions = GetSafariOptions(executionConfiguration.ClassFullName);

                if (executionConfiguration.ShouldCaptureHttpTraffic && _proxyService.IsEnabled)
                {
                    safariOptions.Proxy = webDriverProxy;
                }

                wrappedWebDriver = new SafariDriver(safariOptions);

                var safariPageLoadTimeout = ConfigurationService.GetSection <WebSettings>().Safari.PageLoadTimeout;
                wrappedWebDriver.Manage().Timeouts().PageLoad = TimeSpan.FromSeconds(safariPageLoadTimeout);
                var safariScriptTimeout = ConfigurationService.GetSection <WebSettings>().Safari.ScriptTimeout;
                wrappedWebDriver.Manage().Timeouts().AsynchronousJavaScript = TimeSpan.FromSeconds(safariScriptTimeout);
                BrowserSettings = ConfigurationService.GetSection <WebSettings>().Safari;
                break;

            default:
                throw new NotSupportedException($"Not supported browser {executionConfiguration.BrowserType}");
            }

            return(wrappedWebDriver);
        }
コード例 #31
0
        public IWebDriver StartChromeBrowser()
        {
            var options = new ChromeOptions();
            
            // Add the WebDriver proxy capability.
            if (Config.Settings.httpProxy.useProxy)
            {
                var proxy = new OpenQA.Selenium.Proxy();
                proxy.HttpProxy = "localhost:" + TestBase.proxy.proxyPort;
                options.Proxy = proxy;
            }

            return new ChromeDriver(options);
        }
コード例 #32
0
 public ProxyUtils(string urlProxy)
 {
     _proxyInstance = new OpenQA.Selenium.Proxy {
         HttpProxy = urlProxy, SslProxy = urlProxy, Kind = ProxyKind.Manual, IsAutoDetect = false
     };
 }
コード例 #33
0
        public IWebDriver StartSafariBrowser()
        {
            var options = new SafariOptions();

            // Add the WebDriver proxy capability.
            if (Config.Settings.httpProxy.startProxy)
            {
                var proxy = new OpenQA.Selenium.Proxy();
                proxy.HttpProxy = "localhost:" + TestBase.proxy.proxyPort;
                options.AddAdditionalCapability("proxy", proxy);
            }

            return new SafariDriver(options);
        }
コード例 #34
0
        public IWebDriver StartIEBrowser()
        {
            var options = new InternetExplorerOptions();
            options.IntroduceInstabilityByIgnoringProtectedModeSettings = true;
            options.IgnoreZoomLevel = true;
            if (Config.Settings.httpProxy.startProxy)
            {
                var proxy = new OpenQA.Selenium.Proxy();
                proxy.HttpProxy = "localhost:" + TestBase.proxy.proxyPort;
                options.Proxy = proxy;
                options.UsePerProcessProxy = true;
            }

            return new InternetExplorerDriver(options);
        }
コード例 #35
0
 protected override IWebDriver CreateDriver(Proxy proxy)
 {
     return CreateFirefoxDriver(proxy);
 }
コード例 #36
0
 /// <summary>
 /// Performs the initialize of the browser.
 /// </summary>
 /// <param name="driverFolder">The driver folder.</param>
 /// <param name="proxy">The proxy.</param>
 /// <returns>
 /// The web driver.
 /// </returns>
 protected override IWebDriver PerformInitialize(string driverFolder, Proxy proxy)
 {
     var profile = new FirefoxProfile();
     profile.SetProxyPreferences(proxy);
     return new FirefoxDriver(profile);
 }
コード例 #37
0
        public static IWebDriver Create(BrowserConfiguration executionConfiguration)
        {
            ProcessCleanupService.KillAllDriversAndChildProcessesWindows();

            DisposeDriverService.TestRunStartTime = DateTime.Now;

            BrowserConfiguration = executionConfiguration;
            var wrappedWebDriver = default(IWebDriver);

            _proxyService = ServicesCollection.Current.Resolve <ProxyService>();
            var webDriverProxy = new OpenQA.Selenium.Proxy
            {
                HttpProxy = $"http://127.0.0.1:{_proxyService.Port}",
                SslProxy  = $"http://127.0.0.1:{_proxyService.Port}",
            };

            switch (executionConfiguration.ExecutionType)
            {
            case ExecutionType.Regular:
                wrappedWebDriver = InitializeDriverRegularMode(executionConfiguration, webDriverProxy);
                break;

            case ExecutionType.Grid:
                var gridUri = ConfigurationService.GetSection <WebSettings>().Remote.GridUri;
                if (gridUri == null || !Uri.IsWellFormedUriString(gridUri.ToString(), UriKind.Absolute))
                {
                    throw new ArgumentException("To execute your tests in WebDriver Grid mode you need to set the gridUri in the browserSettings file.");
                }

                Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
                wrappedWebDriver = new RemoteWebDriver(gridUri, executionConfiguration.DriverOptions);
                var gridPageLoadTimeout = ConfigurationService.GetSection <WebSettings>().Remote.PageLoadTimeout;
                wrappedWebDriver.Manage().Timeouts().PageLoad = TimeSpan.FromSeconds(gridPageLoadTimeout);
                var gridScriptTimeout = ConfigurationService.GetSection <WebSettings>().Remote.ScriptTimeout;
                wrappedWebDriver.Manage().Timeouts().AsynchronousJavaScript = TimeSpan.FromSeconds(gridScriptTimeout);
                BrowserSettings = ConfigurationService.GetSection <WebSettings>().Remote;
                ChangeWindowSize(executionConfiguration.BrowserType, executionConfiguration.Size, wrappedWebDriver);
                break;

            case ExecutionType.BrowserStack:
                var browserStackUri = ConfigurationService.GetSection <WebSettings>().BrowserStack.GridUri;
                BrowserSettings = ConfigurationService.GetSection <WebSettings>().BrowserStack;
                if (browserStackUri == null || !Uri.IsWellFormedUriString(browserStackUri.ToString(), UriKind.Absolute))
                {
                    throw new ArgumentException("To execute your tests in BrowserStack you need to set the gridUri in the browserSettings file.");
                }

                wrappedWebDriver = new RemoteWebDriver(browserStackUri, executionConfiguration.DriverOptions);
                var browserStackPageLoadTimeout = ConfigurationService.GetSection <WebSettings>().BrowserStack.PageLoadTimeout;
                wrappedWebDriver.Manage().Timeouts().PageLoad = TimeSpan.FromSeconds(browserStackPageLoadTimeout);
                var browserStackScriptTimeout = ConfigurationService.GetSection <WebSettings>().BrowserStack.ScriptTimeout;
                wrappedWebDriver.Manage().Timeouts().AsynchronousJavaScript = TimeSpan.FromSeconds(browserStackScriptTimeout);
                break;

            case ExecutionType.CrossBrowserTesting:
                var crossBrowserTestingUri = ConfigurationService.GetSection <WebSettings>().CrossBrowserTesting.GridUri;
                BrowserSettings = ConfigurationService.GetSection <WebSettings>().CrossBrowserTesting;
                if (crossBrowserTestingUri == null || !Uri.IsWellFormedUriString(crossBrowserTestingUri.ToString(), UriKind.Absolute))
                {
                    throw new ArgumentException("To execute your tests in CrossBrowserTesting you need to set the gridUri in the browserSettings file.");
                }

                wrappedWebDriver = new RemoteWebDriver(crossBrowserTestingUri, executionConfiguration.DriverOptions);
                var crossBrowserTestingPageLoadTimeout        = ConfigurationService.GetSection <WebSettings>().CrossBrowserTesting.PageLoadTimeout;
                wrappedWebDriver.Manage().Timeouts().PageLoad = TimeSpan.FromSeconds(crossBrowserTestingPageLoadTimeout);
                var crossBrowserTestingScriptTimeout          = ConfigurationService.GetSection <WebSettings>().CrossBrowserTesting.ScriptTimeout;
                wrappedWebDriver.Manage().Timeouts().AsynchronousJavaScript = TimeSpan.FromSeconds(crossBrowserTestingScriptTimeout);
                break;

            case ExecutionType.SauceLabs:
                var sauceLabsSettings = ConfigurationService.GetSection <WebSettings>().SauceLabs;
                var sauceLabsUri      = sauceLabsSettings.GridUri;
                if (sauceLabsUri == null || !Uri.IsWellFormedUriString(sauceLabsUri.ToString(), UriKind.Absolute))
                {
                    throw new ArgumentException("To execute your tests in SauceLabs you need to set the gridUri in the browserSettings file.");
                }

                wrappedWebDriver = new RemoteWebDriver(sauceLabsUri, executionConfiguration.DriverOptions);
                var sauceLabsPageLoadTimeout = sauceLabsSettings.PageLoadTimeout;
                wrappedWebDriver.Manage().Timeouts().PageLoad = TimeSpan.FromSeconds(sauceLabsPageLoadTimeout);
                var sauceLabsScriptTimeout = sauceLabsSettings.ScriptTimeout;
                wrappedWebDriver.Manage().Timeouts().AsynchronousJavaScript = TimeSpan.FromSeconds(sauceLabsScriptTimeout);
                BrowserSettings = sauceLabsSettings;
                break;
            }

            if (executionConfiguration.BrowserType != BrowserType.Edge)
            {
                FixDriverCommandExecutionDelay((RemoteWebDriver)wrappedWebDriver);
            }

            ChangeWindowSize(executionConfiguration.BrowserType, executionConfiguration.Size, wrappedWebDriver);

            return(wrappedWebDriver);
        }
コード例 #38
0
 protected override IWebDriver CreateDriver(Proxy proxy)
 {
     return CreateChromeDriver(proxy);
 }
コード例 #39
0
ファイル: VKParser.cs プロジェクト: VodemSharp/TagSearcher
        public VKParser(string id, string proxy_host, string proxy_port, string vk_login, string vk_password, QueryType queryType)
        {
            Id          = id;
            ProxyHost   = proxy_host;
            ProxyPort   = proxy_port;
            VK_Login    = vk_login;
            VK_Password = vk_password;
            QueryType   = queryType;

            Data = String.Format("{0}/{1}/{2}/{3}", ProxyHost, ProxyPort, VK_Login, VK_Password);

#pragma warning disable CS0618 // Type or member is obsolete

            PhantomJSDriverService service = PhantomJSDriverService.CreateDefaultService(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location));

            PhantomJSOptions options = null;

            if (ProxyHost != "0.0.0.0" && ProxyPort != "0")
            {
                OpenQA.Selenium.Proxy proxy = new OpenQA.Selenium.Proxy();
                proxy.HttpProxy = String.Format(ProxyHost + ":" + ProxyPort);
                proxy.Kind      = ProxyKind.Manual;

                service.ProxyType = "http";
                service.Proxy     = proxy.HttpProxy;

                options = new PhantomJSOptions {
                    Proxy = proxy
                };
            }

            service.HideCommandPromptWindow = true;
            service.IgnoreSslErrors         = true;
            service.SslProtocol             = "any";
            service.WebSecurity             = false;
            service.LocalToRemoteUrlAccess  = true;
            service.LoadImages = false;

            if (options == null)
            {
                Browser = new OpenQA.Selenium.PhantomJS.PhantomJSDriver(service);
            }
            else
            {
                Browser = new OpenQA.Selenium.PhantomJS.PhantomJSDriver(service, options);
            }

            // login

            FileHelper.WriteToLog("Login...", Data);

            Browser.Navigate().GoToUrl("https://m.vk.com/");

            WebDriverWait ww          = new WebDriverWait(Browser, TimeSpan.FromSeconds(10));
            IWebElement   SearchInput = ww.Until(ExpectedConditions.ElementIsVisible(By.CssSelector("input[name='email']")));

            SearchInput.SendKeys(VK_Login);
            SearchInput = Browser.FindElement(By.CssSelector("input[name='pass']"));
            SearchInput.SendKeys(VK_Password + OpenQA.Selenium.Keys.Enter);

            FileHelper.WriteToLog("Login complete!", Data);
        }
コード例 #40
0
        private QA.IWebDriver InitWebDriver()
        {
            QA.IWebDriver theDriver = null;
            switch (this.browser)
            {
            case Browsers.IE:
            {
                InternetExplorerDriverService driverService = InternetExplorerDriverService.CreateDefaultService(Application.StartupPath + "\\drivers\\");
                driverService.HideCommandPromptWindow = true;
                driverService.SuppressInitialDiagnosticInformation = true;
                ds = driverService;
                QA.IE.InternetExplorerOptions _ieOptions = new QA.IE.InternetExplorerOptions();
                _ieOptions.IntroduceInstabilityByIgnoringProtectedModeSettings = true;
                theDriver = new QA.IE.InternetExplorerDriver(driverService, _ieOptions);
                ProcessID = driverService.ProcessId;
            }; break;

            case Browsers.PhantomJS:
            {
                PhantomJSDriverService driverService = PhantomJSDriverService.CreateDefaultService(Application.StartupPath + "\\Drivers\\");
                driverService.HideCommandPromptWindow = true;
                driverService.SuppressInitialDiagnosticInformation = true;
                ds = driverService;

                theDriver = new QA.PhantomJS.PhantomJSDriver(driverService);
            }; break;

            case Browsers.Chrome:
            {
                ChromeDriverService driverService = ChromeDriverService.CreateDefaultService(Application.StartupPath + "\\drivers\\");
                driverService.HideCommandPromptWindow = true;
                driverService.SuppressInitialDiagnosticInformation = true;
                ds = driverService;

                ChromeOptions options = new QA.Chrome.ChromeOptions();
                options.AddUserProfilePreference("profile.managed_default_content_settings.images", _IsLoadPicture ? 1 : 2);
                options.AddUserProfilePreference("profile.managed_default_content_settings.javascript", _IsLoadJS ? 1 : 2);

                //options.AddArgument(@"--user-data-dir=" + cache_dir);
                //string dir = string.Format(@"user-data-dir={0}", ConfigManager.GetInstance().UserDataDir);
                //options.AddArguments(dir);

                //options.AddArgument("--no-sandbox");
                //options.AddArgument("--disable-dev-shm-usage");
                //options.AddArguments("--disable-extensions"); // to disable extension
                //options.AddArguments("--disable-notifications"); // to disable notification
                //options.AddArguments("--disable-application-cache"); // to disable cache
                try
                {
                    if (_timeout == 60)
                    {
                        theDriver = new QA.Chrome.ChromeDriver(driverService, options, new TimeSpan(0, 0, 40));
                    }
                    else
                    {
                        theDriver = new QA.Chrome.ChromeDriver(driverService, options, new TimeSpan(0, 0, _timeout));
                    }
                }
                catch (Exception ex)
                {
                }
                ProcessID = driverService.ProcessId;
            }; break;

            case Browsers.Firefox:
            {
                var driverService = FirefoxDriverService.CreateDefaultService(Application.StartupPath + "\\drivers\\");
                driverService.HideCommandPromptWindow = true;
                driverService.SuppressInitialDiagnosticInformation = true;
                ds = driverService;

                FirefoxProfile profile = new FirefoxProfile();
                try
                {
                    if (_doproxy == "1")
                    {
                        string proxy = "";
                        try
                        {
                            if (_IsUseNewProxy == false)
                            {
                                proxy = GetProxyA();
                            }
                            else
                            {
                                //TO DO 获取芝麻代理
                                hi.URL = "http:......?你的代理地址";        // ConfigManager.GetInstance().ProxyUrl;
                                hr     = hh.GetContent(hi);
                                if (hr.StatusCode == System.Net.HttpStatusCode.OK)
                                {
                                    if (hr.Content.Contains("您的套餐余量为0"))
                                    {
                                        proxy = "";
                                    }
                                    if (hr.Content.Contains("success") == false)
                                    {
                                        proxy = "";
                                    }

                                    JObject j = JObject.Parse(hr.Content);
                                    foreach (var item in j)
                                    {
                                        foreach (var itemA in item.Value)
                                        {
                                            if (itemA.ToString().Contains("expire_time"))
                                            {
                                                if (DateTime.Now.AddHours(2) < DateTime.Parse(itemA["expire_time"].ToString()))
                                                {
                                                    proxy = itemA["ip"].ToString() + ":" + itemA["port"].ToString();
                                                    break;
                                                }
                                            }
                                        }
                                        if (proxy != "")
                                        {
                                            break;
                                        }
                                    }
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                        }

                        if (proxy != "" && proxy.Contains(":"))
                        {
                            OpenQA.Selenium.Proxy proxyF = new OpenQA.Selenium.Proxy();
                            proxyF.HttpProxy = proxy;
                            proxyF.FtpProxy  = proxy;
                            proxyF.SslProxy  = proxy;
                            profile.SetProxyPreferences(proxyF);
                            // 使用代理
                            profile.SetPreference("network.proxy.type", 1);
                            //ProxyUser-通行证书 ProxyPass-通行密钥
                            profile.SetPreference("username", "你的账号");
                            profile.SetPreference("password", "你的密码");

                            // 所有协议公用一种代理配置,如果单独配置,这项设置为false
                            profile.SetPreference("network.proxy.share_proxy_settings", true);

                            // 对于localhost的不用代理,这里必须要配置,否则无法和webdriver通讯
                            profile.SetPreference("network.proxy.no_proxies_on", "localhost");
                        }
                    }
                }
                catch (Exception ex)
                {
                }

                //profile.SetPreference("permissions.default.image", 2);
                // 关掉flash
                profile.SetPreference("dom.ipc.plugins.enabled.libflashplayer.so", false);
                FirefoxOptions options = new FirefoxOptions();
                options.Profile = profile;
                theDriver       = new QA.Firefox.FirefoxDriver(driverService, options, TimeSpan.FromMinutes(1));
                ProcessID       = driverService.ProcessId;
            }; break;

            case Browsers.Safari:
            {
                SafariDriverService driverService = SafariDriverService.CreateDefaultService(Application.StartupPath + "\\Drivers\\");
                driverService.HideCommandPromptWindow = true;
                driverService.SuppressInitialDiagnosticInformation = true;
                ds        = driverService;
                theDriver = new QA.Safari.SafariDriver(driverService);
                ProcessID = driverService.ProcessId;
            }; break;

            default:
            {
                QA.IE.InternetExplorerOptions _ieOptions = new QA.IE.InternetExplorerOptions();
                _ieOptions.IntroduceInstabilityByIgnoringProtectedModeSettings = true;
                theDriver = new QA.IE.InternetExplorerDriver(_ieOptions);
            }; break;
            }
            return(theDriver);
        }
コード例 #41
0
        public IWebDriver StartPhantomJSBrowser()
        {
            var options = new PhantomJSOptions();

            if (Config.Settings.httpProxy.useProxy)
            {
                var proxy = new OpenQA.Selenium.Proxy();
                proxy.HttpProxy = Config.Settings.httpProxy.proxyUrl + ":" + TestBase.proxy.proxyPort;
                proxy.SslProxy = Config.Settings.httpProxy.proxyUrl + ":" + TestBase.proxy.proxyPort;
                proxy.FtpProxy = Config.Settings.httpProxy.proxyUrl + ":" + TestBase.proxy.proxyPort;
                options.AddAdditionalCapability("proxy", proxy);
            }

            return new PhantomJSDriver(options);
        }