Пример #1
0
        public static IWebDriver GetChromeWebDriver(string userDataDir, string chromeDriverExePath)
        {
            // workaround to a bug in dot net core that makes findelement so slow
            // https://github.com/SeleniumHQ/selenium/issues/4988
            // change the chrome driver to run on another port and 127.0.0.1 instead of localhost

            // add chromedriver to the PATH
            var    chromeDriverDirectory = new FileInfo(chromeDriverExePath).FullName;
            string pathEnv = Environment.GetEnvironmentVariable("PATH");

            pathEnv += ";" + chromeDriverDirectory;
            Environment.SetEnvironmentVariable("PATH", pathEnv);

            ChromeDriverService service = ChromeDriverService.CreateDefaultService();

            service.Port = 5555; // Any port value.
            service.Start();

            ChromeOptions options          = new ChromeOptions();
            string        userDataArgument = string.Format("user-data-dir={0}", userDataDir);

            options.AddArguments(userDataArgument);
            options.AddArguments("--start-maximized");
            options.AddArgument("--log-level=3");
            //options.AddArguments("--ignore-certificate-errors");
            //options.AddArguments("--ignore-ssl-errors");
            //options.AddArgument("--headless");

            //IWebDriver driver = new ChromeDriver(chromeDriverExePath, options);
            IWebDriver driver = new RemoteWebDriver(new Uri("http://127.0.0.1:5555"), options);

            return(driver);
        }
Пример #2
0
        public void Test_Driver2()
        {
            string pathToChromeDriver   = @"G:\";
            ChromeDriverService service = ChromeDriverService.CreateDefaultService(pathToChromeDriver);

            service.Port = 5555; // Some port value.
            service.Start();

            var chromeOptions = new ChromeOptions();
            //chromeOptions.BinaryLocation = pathToChromeDriver;
            var driver = new RemoteWebDriver(new Uri("http://*****:*****@"G:\Programming\Git\SelenItEasy\SelenItEasy\Tests\Site\Index.html");

            var checkbox1 = driver.FindElement(By.Id("checkbox1"));
            var checkbox2 = driver.FindElement(By.Id("checkbox2"));

            var selected1 = checkbox1.Selected;

            checkbox1.Click();
            var selected2 = checkbox1.Selected;

            var selected3 = checkbox2.Selected;

            checkbox2.Click();
            var selected4 = checkbox2.Selected;

            driver.Quit();
        }
Пример #3
0
        //private ChromeDriverService _driverService = null;
        //private ChromeOptions _options = null;

        //public ChromeWebDriverManager(string driverDirectory = null)
        //{
        //    if (driverDirectory != null)
        //        _driverService = ChromeDriverService.CreateDefaultService(driverDirectory);
        //    else
        //        _driverService = ChromeDriverService.CreateDefaultService();
        //    _driverService.HideCommandPromptWindow = true;
        //    _driverService.SuppressInitialDiagnosticInformation = true;
        //    _driverService.Start();
        //    _options = new ChromeOptions();
        //    _options.LeaveBrowserRunning = true;
        //}

        public static IWebDriver CreateWebDriver(string driverDirectory = null)
        {
            ChromeDriverService service = CreateDriverService(driverDirectory);

            // execute "chromedriver.exe"
            service.Start();
            return(new ChromeDriver(service, CreateOptions()));
        }
        static void StartService()
        {
            DriverService = ChromeDriverService.CreateDefaultService(AppContext.BaseDirectory);
            DriverService.Start();

            ChromeOptions = new ChromeOptions();
            //ChromeOptions.AddArgument("--headless");
        }
Пример #5
0
        public static IWebDriverWrapper RequestDriver()
        {
            if (DriverCount == 0)
            {
                ChromeDriverService.Start();
            }

            return(new ChromeDriver(ChromeDriverService).ToWrapper());;
        }
Пример #6
0
        public static ChromeDriverService GetChromeDriverService()
        {
            chromeDriverService = ChromeDriverService.CreateDefaultService(FileUtils.GetCurrentlyExecutingDirectory());
            if (chromeDriverService.IsRunning)
            {
                chromeDriverService.Dispose();
            }
            chromeDriverService.Start();
            chromeDriverService.LogPath = appConfigMember.ChromeLogFileLocation;
            chromeDriverService.EnableVerboseLogging = true;

            return(chromeDriverService);
        }
Пример #7
0
        /// <summary>
        /// Creates a web driver.
        /// </summary>
        /// <param name="driverPath">Path to the folder containg the web driver.</param>
        /// <param name="startOptions">Null allowed. Providing null falls back to default BrowserStartOptions.</param>
        /// <returns>An instance of Chrome Driver.</returns>
        public static IWebDriver Create(string driverPath, BrowserStartOptions startOptions)
        {
            ChromeDriverService service = ChromeDriverService.CreateDefaultService(driverPath);

            service.Port = 5555; // Some port value.
            service.Start();

            var chromeOptions = CreateOptions(startOptions);

            IWebDriver webDriver = new RemoteWebDriver(new Uri("http://127.0.0.1:5555"), chromeOptions);

            return(webDriver);
        }
Пример #8
0
        private void CreateDriver()
        {
            srv.Start();
            Properties.Settings.Default.AcilanServisler.Add(srv.ProcessId.ToString());
            Properties.Settings.Default.Save();
            ChromeOptions options = new ChromeOptions();

            options.AddArgument("disable-infobars");
            driver = new ChromeDriver(srv, options);
            driver.Manage().Timeouts().PageLoad = new TimeSpan(0, 0, ZamanAsimi);
            driver.Manage().Window.Minimize();
            DriverChanged();
            Optimizasyon.Delagate(this, () => { this.Focus(); });
        }
Пример #9
0
        public static IWebDriver GetDriver(string BrowserName)
        {
            IWebDriver result = null;

            switch (BrowserName.ToLower())
            {
            case "chrome":
                ChromeDriverService cService = ChromeDriverService.CreateDefaultService();
                cService.Start();
                serviceId = cService.ProcessId;
                service   = cService;
                result    = new ThreadLocal <IWebDriver>(() => { return(new EventFiringWebDriver(new ChromeDriver())); }).Value;
                break;

            case "ie":
                InternetExplorerDriverService ieService = InternetExplorerDriverService.CreateDefaultService();
                ieService.Start();
                serviceId = ieService.ProcessId;
                service   = ieService;
                var options = new InternetExplorerOptions {
                    IgnoreZoomLevel = true
                };
                result = new ThreadLocal <IWebDriver>(() => { return(new EventFiringWebDriver(new InternetExplorerDriver(ieService, options))); }).Value;
                break;

            case "firefox":
                FirefoxDriverService ffService = FirefoxDriverService.CreateDefaultService();
                ffService.Start();
                serviceId = ffService.ProcessId;
                service   = ffService;
                result    = new ThreadLocal <IWebDriver>(() => { return(new EventFiringWebDriver(new FirefoxDriver(ffService))); }).Value;
                break;

            default:
                throw new Exception("Bad Driver Identifier: " + BrowserName + ".");
            }
            //result.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(60));
            result.Manage().Timeouts().SetPageLoadTimeout(TimeSpan.FromSeconds(60));
            result.Manage().Window.Maximize();

            wait   = new WebDriverWait(result, new TimeSpan(0, 0, 30));
            driver = result;
            return(result);
        }
Пример #10
0
 public void Setup()
 {
     ChromeService = ChromeDriverService.CreateDefaultService();
     ChromeService.Start();
     //Chrome = new RemoteWebDriver(ChromeService.ServiceUrl, DesiredCapabilities.Chrome());
 }
    static void Main(string[] args)
    {
        string        executablePath = null;
        string        executableName = null;
        bool          useService     = false;
        Uri           remotePort     = null;
        ChromeOptions chromeOptions  = new ChromeOptions();
        string        logPath        = null;
        string        url            = "http://www.google.com/";
        string        htmlPath       = null;
        bool          append         = false;
        bool          name           = false;
        bool          title          = false;
        bool          quit           = true;
        bool          testCookies    = false;
        bool          testPosition   = false;
        bool          testSize       = false;

        for (int argi = 0; argi < args.Length; argi++)
        {
            if (!args[argi].StartsWith("-"))
            {
                Usage();
            }

            if (args[argi] == "-driver" && argi + 1 < args.Length)
            {
                executablePath = Path.GetFullPath(args[++argi]);
                if (File.Exists(executablePath))
                {
                    executableName = Path.GetFileName(executablePath);
                    executablePath = Path.GetDirectoryName(executablePath);
                }
            }
            else if (args[argi] == "-chrome" && argi + 1 < args.Length)
            {
                chromeOptions.BinaryLocation = args[++argi];
            }
            else if (args[argi] == "-data" && argi + 1 < args.Length)
            {
                chromeOptions.AddArgument("user-data-dir=" + args[++argi]);
            }
            else if (args[argi] == "-service")
            {
                useService = true;
            }
            else if (args[argi] == "-remote" && argi + 1 < args.Length)
            {
                remotePort = new Uri(args[++argi]);
            }
            else if (args[argi] == "-url" && argi + 1 < args.Length)
            {
                url = args[++argi];
            }
            else if (args[argi] == "-log" && argi + 1 < args.Length)
            {
                logPath = args[++argi];
            }
            else if (args[argi] == "-append")
            {
                append = true;
            }
            else if (args[argi] == "-save" && argi + 1 < args.Length)
            {
                htmlPath = args[++argi];
            }
            else if (args[argi] == "-debug" && argi + 1 < args.Length)
            {
                // Chrome should have been started with --remote-debugging-port=port
                chromeOptions.DebuggerAddress = args[++argi];
            }
            else if (args[argi] == "-name")
            {
                name = true;
            }
            else if (args[argi] == "-title")
            {
                title = true;
            }
            else if (args[argi] == "-cookies")
            {
                testCookies = true;
            }
            else if (args[argi] == "-position")
            {
                testPosition = true;
            }
            else if (args[argi] == "-size")
            {
                testSize = true;
            }
            else if (args[argi] == "-keep")
            {
                quit = false;
            }
            else
            {
                Usage();
            }
        }

        if (useService && remotePort != null)
        {
            Console.Error.WriteLine("Can't use both -service and -remote options");
            Environment.Exit(1);
        }

        ChromeDriverService service =
            executablePath == null?ChromeDriverService.CreateDefaultService() :
                executableName == null?ChromeDriverService.CreateDefaultService(executablePath) :
                    ChromeDriverService.CreateDefaultService(executablePath, executableName);

        if (logPath != null)
        {
            service.LogPath = logPath;
            service.EnableVerboseLogging = true;
        }

        if (append)
        {
            service.EnableAppendLog = true;
        }

        if (useService)
        {
            service.Start();
            remotePort = service.ServiceUrl;
            Console.WriteLine("Service URL: {0}", remotePort);
        }

        RemoteWebDriver driver;

        if (remotePort != null)
        {
            driver = new RemoteWebDriver(remotePort, chromeOptions);
        }
        else
        {
            driver = new ChromeDriver(service, chromeOptions);
        }

        if (name)
        {
            Console.WriteLine("Browser name: {0}", driver.Capabilities.GetCapability("browserName"));
        }

        driver.Navigate().GoToUrl(url);

        if (title)
        {
            Console.WriteLine("Page title: {0}", driver.Title);
            Console.WriteLine("Page URL: {0}", driver.Url);
        }

        if (htmlPath != null)
        {
            using (TextWriter f = File.CreateText(htmlPath))
            {
                f.Write(driver.PageSource);
            }
        }

        if (testCookies)
        {
            ICookieJar cookieJar = driver.Manage().Cookies;
            cookieJar.AddCookie(new Cookie("foo", "bar", "/"));
            Console.WriteLine("Cookies:");
            foreach (Cookie cookie in cookieJar.AllCookies)
            {
                Console.WriteLine("\t{0}", cookie);
            }
        }

        if (testPosition)
        {
            IWindow window   = driver.Manage().Window;
            Point   position = window.Position;
            int     x        = position.X;
            int     y        = position.Y;
            Console.WriteLine("Current window position ({0}, {1})", x, y);

            x += 100;
            y += 100;
            Console.WriteLine("Attempting to change window position to ({0}, {1})", x, y);
            window.Position = new Point(x, y);

            position = window.Position;
            Console.WriteLine("New window position ({0}, {1})", position.X, position.Y);
        }

        if (testSize)
        {
            IWindow window = driver.Manage().Window;
            Size    size   = window.Size;
            int     width  = size.Width;
            int     height = size.Height;
            Console.WriteLine("Current window size {0}x{1}", width, height);

            width  /= 2;
            height /= 2;
            Console.WriteLine("Attempting to change window size to {0}x{1}", width, height);
            window.Size = new Size(width, height);

            size = window.Size;
            Console.WriteLine("New window size {0}x{1}", size.Width, size.Height);
        }

        if (quit)
        {
            Thread.Sleep(3000);
            driver.Quit();
        }
    }
Пример #12
0
        public static void Test_Selenium_Chrome_02()
        {
            Trace.WriteLine("Test_Selenium_Chrome_02");

            // from http://www.seleniumhq.org/docs/03_webdriver.jsp

            // Create a new instance of the Firefox driver.

            // Notice that the remainder of the code relies on the interface,
            // not the implementation.

            // Further note that other drivers (InternetExplorerDriver,
            // ChromeDriver, etc.) will require further configuration
            // before this example will work. See the wiki pages for the
            // individual drivers at http://code.google.com/p/selenium/wiki
            // for further information.
            //string chromeDriverDirectory = @"$Root$\..\library\Selenium\chrome.driver".zGetRunSourceProjectVariableValue().zRootPath(RunSource.CurrentRunSource.ProjectDirectory);
            string chromeDriverDirectory = GetChromeDriverDirectory();

            Trace.WriteLine("  ChromeDriverService service = ChromeDriverService.CreateDefaultService(\"{0}\");", chromeDriverDirectory);
            ChromeDriverService service = ChromeDriverService.CreateDefaultService(chromeDriverDirectory);

            service.HideCommandPromptWindow = true;
            service.SuppressInitialDiagnosticInformation = true;
            Trace.WriteLine("  service.LogPath : \"{0}\"", service.LogPath);
            Trace.WriteLine("  service.Start();");
            // execute "chromedriver.exe"
            service.Start();
            Trace.WriteLine("  service.ProcessId : {0}", service.ProcessId);
            ChromeOptions chromeOptions = new ChromeOptions();

            chromeOptions.LeaveBrowserRunning = true;
            Trace.WriteLine("  IWebDriver driver = new ChromeDriver(service, chromeOptions);");
            IWebDriver driver = new ChromeDriver(service, chromeOptions);

            Trace.WriteLine("  driver.CurrentWindowHandle : \"{0}\"", driver.CurrentWindowHandle);
            Trace.WriteLine("  driver.WindowHandles.Count : {0}", driver.WindowHandles.Count);
            foreach (string windowHandle in driver.WindowHandles)
            {
                Trace.WriteLine("  windowHandle : \"{0}\"", windowHandle);
            }

            //Notice navigation is slightly different than the Java version
            //This is because 'get' is a keyword in C#
            Trace.WriteLine("  driver.Navigate().GoToUrl(\"http://www.google.com/\");");
            driver.Navigate().GoToUrl("http://www.google.com/");

            // Find the text input element by its name
            Trace.WriteLine("  IWebElement query = driver.FindElement(By.Name(\"q\"));");
            IWebElement query = driver.FindElement(By.Name("q"));

            // Enter something to search for
            Trace.WriteLine("  query.SendKeys(\"Cheese\");");
            query.SendKeys("Cheese");

            // Now submit the form. WebDriver will find the form for us from the element
            Trace.WriteLine("  query.Submit();");
            query.Submit();

            // Google's search is rendered dynamically with JavaScript.
            // Wait for the page to load, timeout after 10 seconds
            Trace.WriteLine("  WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(30));");
            WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(30));

            Trace.WriteLine("  wait.Until((d) => { return d.Title.ToLower().StartsWith(\"cheese\"); });");
            wait.Until((d) => { return(d.Title.ToLower().StartsWith("cheese")); });

            // Should see: "Cheese - Google Search"
            //Trace.WriteLine("Page title is : " + driver.Title);
            Trace.WriteLine("  driver.Title : \"{0}\"", driver.Title);

            Trace.WriteLine("  Thread.Sleep(30000);");
            Thread.Sleep(30000);

            //Close the browser
            Trace.WriteLine("  driver.Quit();");
            driver.Quit();
            service.Dispose();
        }
 public Chrome()
 {
     _chromeDriverService      = ChromeDriverService.CreateDefaultService();
     _chromeDriverService.Port = _port;
     _chromeDriverService.Start();
 }
Пример #14
0
        private static void Init(BrowserType type, string url, PlatformType platform, string dirverPath)
        {
            BrowserInfo         browserString = BrowserFinder.Find(type);
            DesiredCapabilities capabilities  = new DesiredCapabilities();

            switch (type)
            {
            case BrowserType.InternetExplorer:

                InternetExplorerOptions op = new InternetExplorerOptions();
                op.IntroduceInstabilityByIgnoringProtectedModeSettings = true;
                op.InitialBrowserUrl = url;
                op.AddAdditionalCapability("Platform", platform.ToString());

                InternetExplorerDriverService services = InternetExplorerDriverService.CreateDefaultService(dirverPath);
                services.Start();

                //webDriver = new InternetExplorerDriver(services, op);
                break;

            case BrowserType.Firefox:
                capabilities          = DesiredCapabilities.Firefox();
                capabilities.Platform = new Platform(platform);

                //webDriver = new RemoteWebDriver(capabilities);

                break;

            case BrowserType.Chrome:

                ChromeDriverService service = ChromeDriverService.CreateDefaultService(dirverPath);

                service.Start();

                ChromeOptions opts = new ChromeOptions();
                opts.AddAdditionalCapability("Platform", platform.ToString());

                //webDriver = new ChromeDriver(service, opts);
                break;

            case BrowserType.Android:
                //webDriver = new AndroidDriver();
                break;

            case BrowserType.Safari:
                SafariDriverServer server = new SafariDriverServer();
                server.Start();

                SafariDriverExtension ext = new SafariDriverExtension();
                ext.Install();

                SafariOptions opt = new SafariOptions();
                opt.AddAdditionalCapability("Platform", platform.ToString());

                capabilities          = DesiredCapabilities.Safari();
                capabilities.Platform = new Platform(platform);

                //webDriver = new SafariDriver(opt);

                break;

            default:
                capabilities          = DesiredCapabilities.Firefox();
                capabilities.Platform = new Platform(platform);
                //webDriver = new RemoteWebDriver(DesiredCapabilities.Firefox());
                break;
            }

            selenim = new WebDriverBackedSelenium(webDriver, url);
        }
Пример #15
0
        private void AMZ_LOGIN_BTN_Click(object sender, EventArgs e)
        {
            try
            {
                if (AREAID.Text == "选择地区")
                {
                    MessageBox.Show("请先选择地区", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                if (COOKIE_TEXT.Text != "")
                {
                    AMZ_LOGIN_BTN.Text = "正在启动...";
                    string json_cookie = "";
                    json_cookie = COOKIE_TEXT.Text.Replace("\"\\\"", "\"").Replace("\\\"\"", "\"").Replace("\\\"", "\"").Replace("\"\"", "\"").Replace(":\",", ":\"\",");

                    ChromeDriverService chromeDriverService = null;
                    RemoteWebDriver     driver  = null;
                    ChromeOptions       options = new ChromeOptions();
                    string chromeBinPath        = currentWorkingDir + "\\ChromeBin\\chrome.exe";
                    options.BinaryLocation   = chromeBinPath;
                    options.PageLoadStrategy = PageLoadStrategy.None;     //解决载入慢的问题
                    options.AddExcludedArgument("enable-automation");
                    options.AddAdditionalCapability("useAutomationExtension", false);
                    options.AddArgument("--lang=en_US.UTF-8"); //设置英文站点
                    //options.AddArgument("--user-agent=" + RandomUA());   //设置随机UA
                    options.AddArgument("--incognito");        //隐身模式
                    options.AddArgument("--disable-plugins");  //禁用插件
                    options.AddArgument("--disable-infobars"); //解决正受到自动测试软件的控制
                    options.AddArgument("--ignore-ssl-errors");
                    options.AddArgument("--ignore-certificate-errors");
                    options.AddArgument("--disable-extensions");
                    options.AddArgument("--log-level=3");
                    options.AddArgument("--disable-logging");
                    options.AddArgument("--disable-browser-side-navigation");
                    options.AddArgument("--process-per-tab");
                    options.AddArgument("--process-per-site");
                    options.AddArgument("--in-process-plugins");
                    options.AddArgument("--no-sandbox");
                    options.AddArgument("--disable-web-security");
                    options.AddArgument("--local-timezone");
                    options.AddArgument("--disable-webgl");
                    options.AddArgument("--disable-plugins-discovery");
                    options.AddArgument("--disable-timezone-tracking-option");
                    options.AddArgument("--disable-system-timezone-automatic-detection");
                    options.AddArgument("--aggressive-cache-discard");

                    if (chromeDriverService == null || chromeDriverService.ProcessId == 0)
                    {
                        chromeDriverService = ChromeDriverService.CreateDefaultService(currentWorkingDir + "\\ChromeBin\\");
                        chromeDriverService.HideCommandPromptWindow = true;
                        chromeDriverService.Start();
                    }

                    AMZ_LOGIN_BTN.Text = "打开浏览器";
                    Thread.Sleep(800);
                    driver = new RemoteWebDriver(chromeDriverService.ServiceUrl, options.ToCapabilities(), TimeSpan.FromSeconds(90));

                    driver.Manage().Window.Size = new Size(1280, 800);
                    driver.Manage().Window.Position = new Point(0, 0);
                    driver.Manage().Timeouts().PageLoad               = TimeSpan.FromSeconds(30);
                    driver.Manage().Timeouts().ImplicitWait           = TimeSpan.FromSeconds(30);
                    driver.Manage().Timeouts().AsynchronousJavaScript = TimeSpan.FromSeconds(30);

                    Thread.Sleep(1000);
                    driver.ExecuteScript("location.href='https://www.amazon." + AREAID.Text + "/" + 404 + "?ref=googlesearch'");
                    if (driver.Url.Contains("amazon"))
                    {
                        if (insertCookies(driver, json_cookie))
                        {
                            Thread.Sleep(1000);
                            driver.ExecuteScript("location.href='https://www.amazon." + AREAID.Text + "/?ref=nav_logo'");
                            MessageBox.Show("启动完成,使用完成后请点击“关闭浏览器”按钮清理痕迹", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        }
                    }
                }
                else
                {
                    MessageBox.Show("请先填入经过JSON校验通过的COOKIE字符串", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    COOKIE_TEXT.Focus();
                }
            }
            catch (Exception ee)
            {
                MessageBox.Show("执行过程中遇到错误,错误描述:" + ee.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Пример #16
0
 static DriverFactory()
 {
     _service = ChromeDriverService.CreateDefaultService(@"C:\Users\Chase\Desktop\Selenium Practice\SeleniumPracticeTests\SeleniumPracticeTests\Libraries");
     _service.Start();
     _counter = 0;
 }