예제 #1
1
        public static IWebDriver CreateChromeDriverAutoDownload(string downloadDirectory)
        {
            ChromeOptions opts = new ChromeOptions();
            opts.AddUserProfilePreference("download.default_directory", downloadDirectory);
            opts.AddUserProfilePreference("download.prompt_for_download", "false");

            var ChromeDriver = new ChromeDriver(opts);
            ChromeDriver.Manage().Timeouts().SetPageLoadTimeout(new TimeSpan(0, 1, 0));
            ChromeDriver.Manage().Timeouts().ImplicitlyWait(new TimeSpan(0, 0, 1));
            ChromeDriver.Manage().Window.Maximize();
            return ChromeDriver;
        }
 private static IWebDriver GetChromeBrowser()
 {
     var service = ChromeDriverService.CreateDefaultService(Path.GetFullPath(Constants.DriversDirectory));
     var options = new ChromeOptions();
     options.AddUserProfilePreference("download.default_directory", Path.GetFullPath(Constants.WallpapersDirectory));
     var browser = new ChromeDriver(service, options);
     return browser;
 }
예제 #3
0
        private static IWebDriver CreateChromeDriver(string driversDirectory)
        {
            var chromeService = Chrome.ChromeDriverService.CreateDefaultService(driversDirectory);

            chromeService.HideCommandPromptWindow = true;
            var chromeOptions = new Chrome.ChromeOptions
            {
                PageLoadStrategy = PageLoadStrategy.None
            };

            chromeOptions.AddArgument("disable-infobars");
            chromeOptions.AddArgument("--disable-bundled-ppapi-flash");
            chromeOptions.AddArgument("--log-level=3");
            chromeOptions.AddArgument("--silent");
            chromeOptions.AddUserProfilePreference("credentials_enable_service", false);
            chromeOptions.AddUserProfilePreference("profile.password_manager_enabled", false);
            chromeOptions.AddUserProfilePreference("auto-open-devtools-for-tabs", false);
            return(new Chrome.ChromeDriver(chromeService, chromeOptions));
        }
예제 #4
0
        private QA.IWebDriver InitWebDriver(string cache_dir, bool loadImage = true, string useragent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.131 Safari/537.36")
        {
            if (!Directory.Exists(cache_dir))
            {
                Directory.CreateDirectory(cache_dir);
            }
            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.Chrome:
            {
                ChromeDriverService driverService = ChromeDriverService.CreateDefaultService(Application.StartupPath + "\\Drivers\\");
                driverService.Port = new Random().Next(1000, 2000);
                driverService.HideCommandPromptWindow = true;
                driverService.SuppressInitialDiagnosticInformation = true;
                ds = driverService;
                ChromeOptions options = new QA.Chrome.ChromeOptions();
                options.AddArgument("--window-size=" + Screen.PrimaryScreen.WorkingArea.Width + "x" + Screen.PrimaryScreen.WorkingArea.Height);
                options.AddArgument("--disable-gpu");
                options.AddArgument("--disable-extensions");
                options.AddArgument("--no-sandbox");
                options.AddArgument("--disable-dev-shm-usage");
                options.AddArgument("--disable-java");
                options.AddArgument("--user-agent=" + useragent);
                options.AddArgument(@"--user-data-dir=" + cache_dir);
                if (loadImage == false)
                {
                    options.AddUserProfilePreference("profile.managed_default_content_settings.images", 2);        //不加载图片
                }
                theDriver  = new QA.Chrome.ChromeDriver(driverService, options, TimeSpan.FromSeconds(240));
                _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();
                if (loadImage == false)
                {
                    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(240));
                _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;
            }
            //theDriver.Manage().Window.Maximize();
            return(theDriver);
        }
예제 #5
0
        private static IWebDriver CreateNewWebDriver(string webBrowserName, BrowserType type, out IntPtr mainWindowHandle, string driversDirectory)
        {
            webBrowserName = webBrowserName.ToLower();
            IWebDriver     iWebDriver            = null;
            List <Process> processesBeforeLaunch = GetProcesses();
            string         newProcessFilter      = string.Empty;

            switch (type)
            {
            case BrowserType.Chrome:
                var chromeService = Chrome.ChromeDriverService.CreateDefaultService(driversDirectory);
                chromeService.HideCommandPromptWindow = true;
                var chromeOptions = new Chrome.ChromeOptions();
                chromeOptions.PageLoadStrategy = PageLoadStrategy.None;
                chromeOptions.AddArgument("disable-infobars");
                chromeOptions.AddArgument("--disable-bundled-ppapi-flash");
                chromeOptions.AddArgument("--log-level=3");
                chromeOptions.AddArgument("--silent");
                chromeOptions.AddUserProfilePreference("credentials_enable_service", false);
                chromeOptions.AddUserProfilePreference("profile.password_manager_enabled", false);
                chromeOptions.AddUserProfilePreference("auto-open-devtools-for-tabs", false);
                //chromeOptions.AddAdditionalCapability("pageLoadStrategy", "none", true);
                iWebDriver       = new Chrome.ChromeDriver(chromeService, chromeOptions);
                newProcessFilter = "chrome";
                break;

            case BrowserType.Firefox:
                var firefoxService = Firefox.FirefoxDriverService.CreateDefaultService(driversDirectory);
                firefoxService.HideCommandPromptWindow = true;
                iWebDriver       = new Firefox.FirefoxDriver(firefoxService);
                newProcessFilter = "firefox";
                break;

            case BrowserType.InternetExplorer:
                IE.InternetExplorerDriverService ieService = IE.InternetExplorerDriverService.CreateDefaultService(driversDirectory);
                ieService.HideCommandPromptWindow = true;
                IE.InternetExplorerOptions options = new IE.InternetExplorerOptions()
                {
                    IgnoreZoomLevel = true
                };
                iWebDriver       = new IE.InternetExplorerDriver(ieService, options);
                newProcessFilter = "iexplore";
                break;

            case BrowserType.Edge:
                var edgeService = Edge.EdgeDriverService.CreateDefaultService(driversDirectory);
                edgeService.HideCommandPromptWindow = true;
                var edgeOptions = new Edge.EdgeOptions();
                edgeOptions.PageLoadStrategy = PageLoadStrategy.Eager;
                iWebDriver       = new Edge.EdgeDriver(edgeService, edgeOptions);
                newProcessFilter = "edge";
                break;

            default:
                throw new ArgumentException($"Could not launch specified browser '{webBrowserName}'");
            }
            var newProcess = GetNewlyCreatedProcesses(newProcessFilter, processesBeforeLaunch);

            mainWindowHandle = (newProcess != null) ? newProcess.MainWindowHandle : IntPtr.Zero;
            return(iWebDriver);
        }
예제 #6
0
        public WebDriverItem Get()
        {
            CheckRunning();

            if (_webDriverList.Count < _capacity)
            {
                if (_innerQueue.Count == 0)
                {
                    IWebDriver e = null;
                    switch (_browser)
                    {
                        case Browser.Phantomjs:
                            var phantomJsDriverService = PhantomJSDriverService.CreateDefaultService();
                            if (!string.IsNullOrEmpty(_option.Proxy))
                            {
                                phantomJsDriverService.Proxy = _option.Proxy;
                                phantomJsDriverService.ProxyAuthentication = _option.ProxyAuthentication;
                            }
                            e = new PhantomJSDriver(phantomJsDriverService);
                            break;
                        case Browser.Firefox:
                            string path = Environment.ExpandEnvironmentVariables("%APPDATA%") + @"\Mozilla\Firefox\Profiles\";
                            string[] pathsToProfiles = Directory.GetDirectories(path, "*.webdriver", SearchOption.TopDirectoryOnly);
                            FirefoxProfile profile;
                            if (pathsToProfiles.Length == 1)
                            {
                                profile = new FirefoxProfile(pathsToProfiles[0], false);
                            }
                            else
                            {
                                profile = new FirefoxProfile();
                            }
                            if (!_option.AlwaysLoadNoFocusLibrary)
                            {
                                profile.AlwaysLoadNoFocusLibrary = true;
                            }

                            if (!_option.LoadImage)
                            {
                                profile.SetPreference("permissions.default.image", 2);
                            }
                            if (!_option.LoadFlashPlayer)
                            {
                                profile.SetPreference("dom.ipc.plugins.enabled.libflashplayer.so", "false");
                            }
                            if (!string.IsNullOrEmpty(_option.Proxy))
                            {
                                string[] p = _option.Proxy.Split(':');
                                string host = p[0];
                                int port = Convert.ToInt32(p[1]);
                                profile.SetPreference("network.proxy.ftp_port", port);
                                profile.SetPreference("network.proxy.gopher", host);
                                profile.SetPreference("network.proxy.gopher_port", port);
                                profile.SetPreference("network.proxy.http", host);
                                profile.SetPreference("network.proxy.http_port", port);
                                profile.SetPreference("network.proxy.no_proxies_on", "localhost,127.0.0.1,<-loopback>");
                                profile.SetPreference("network.proxy.share_proxy_settings", true);
                                profile.SetPreference("network.proxy.socks", host);
                                profile.SetPreference("network.proxy.socks_port", port);
                                profile.SetPreference("network.proxy.ssl", host);
                                profile.SetPreference("network.proxy.ssl_port", port);
                                profile.SetPreference("network.proxy.type", 1);
                            }

                            e = new FirefoxDriver(profile);
                            break;
                        case Browser.Chrome:
                            ChromeDriverService cds = ChromeDriverService.CreateDefaultService();
                            cds.HideCommandPromptWindow = true;
                            ChromeOptions opt = new ChromeOptions();
                            if (!_option.LoadImage)
                            {
                                opt.AddUserProfilePreference("profile", new { default_content_setting_values = new { images = 2 } });
                            }
                            if (!string.IsNullOrEmpty(_option.Proxy))
                            {
                                opt.Proxy = new Proxy() { HttpProxy = _option.Proxy };
                            }
                            e = new ChromeDriver(cds, opt);
                            break;
                    }
                    _innerQueue.Enqueue(new WebDriverItem(e));
                    _webDriverList.Add(new WebDriverItem(e));
                }
            }

            //else
            //{
            //	while (true)
            //	{
            //		lock (_innerQueue)
            //		{
            //			if (_innerQueue.Count > 0)
            //			{
            //				break;
            //			}
            //			Thread.Sleep(150);
            //		}
            //	}
            //}

            WebDriverItem webDriver;
            while (!_innerQueue.TryDequeue(out webDriver))
            {
                Thread.Sleep(150);
            }

            return webDriver;
        }
예제 #7
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);
        }
예제 #8
-2
        protected RemoteWebDriver GetWebDriver()
        {
            ChromeDriverService cds = ChromeDriverService.CreateDefaultService();
            cds.HideCommandPromptWindow = true;
            ChromeOptions opt = new ChromeOptions();
            opt.AddUserProfilePreference("profile", new { default_content_setting_values = new { images = 2 } });
            RemoteWebDriver webDriver = new ChromeDriver(cds, opt);

            webDriver.Manage().Window.Maximize();
            return webDriver;
        }