AddArguments() public method

Adds arguments to be appended to the Chrome.exe command line.
public AddArguments ( ) : void
return void
Ejemplo n.º 1
2
        public void Login(String loginUrl)
        {
            var options = new ChromeOptions();
            options.AddArguments("--test-type", "--start-maximized");
            options.AddArguments("--test-type", "--ignore-certificate-errors");
            options.BinaryLocation = "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe";
            driver = new ChromeDriver("C:\\Program Files (x86)\\Google\\Chrome\\Application", options);

            driver.Navigate().GoToUrl(loginUrl);

            int timeout = 0;
            while (driver.FindElements(By.ClassName("logbox")).Count == 0 && timeout < 500)
            {
                Thread.Sleep(1);
                timeout++;

            }

            IWebElement element = driver.FindElement(By.ClassName("logbox"));

            IWebElement ElName = element.FindElement(By.Name("username"));
            ElName.Clear();
            ElName.SendKeys(loginName);
            IWebElement ElPassword = element.FindElement(By.Id("password"));
            ElPassword.Clear();
            ElPassword.SendKeys(loginPassword);
            IWebElement ElLogin = element.FindElement(By.Id("IBtnLogin"));
            ElLogin.Click();
        }
        public virtual void InitializeDriver()
        {
            InitializeSettings();

            switch (BrowserType)
            {
                case BrowserType.Chrome:
                    var chromeOptions = new ChromeOptions();
                    chromeOptions.AddArguments(new string[] { "--no-sandbox", "test-type", "--start-maximized" });
                    var chromeDriverService = ChromeDriverService.CreateDefaultService();
                    chromeDriverService.HideCommandPromptWindow = false;
                    Context.Driver = new ChromeDriver(chromeDriverService, chromeOptions, TimeSpan.FromSeconds(300.0));
                break;
                case BrowserType.Firefox:
                    var capabilities = new DesiredCapabilities();
                    capabilities.SetCapability(CapabilityType.UnexpectedAlertBehavior, "dismiss");
                    Context.Driver = new FirefoxDriver(capabilities);
                break;

            }

            Context.Browser = new Browser();
            Context.Driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromMilliseconds(Context.Settings.WaitTimeout));
            Context.Driver.Navigate().GoToUrl("about:blank");
            Context.Driver.SwitchTo().Window(Context.Driver.WindowHandles.First());
        }
Ejemplo n.º 3
1
        public static IWebDriver CreateChromeGridDriver(string profileName, string hubAddress)
        {
            if (hubAddress == null)
            {
                throw new ArgumentException("remoteAddress");
            }

            var chromeOptions = new ChromeOptions();
            if (!string.IsNullOrWhiteSpace(profileName))
            {
                var fileChars = Path.GetInvalidFileNameChars();
                var pathChars = Path.GetInvalidFileNameChars();
                var invalidChars = fileChars.Union(pathChars);

                profileName = String.Join("", profileName.Where(c => !invalidChars.Contains(c)));

                chromeOptions.AddArguments(String.Format("user-data-dir=c:\\ChromeProfiles\\{0}", profileName));
            }

            RemoteWebDriver Driver = new RemoteWebDriver(new Uri(hubAddress), chromeOptions.ToCapabilities());

            Driver.Manage().Timeouts().SetPageLoadTimeout(new TimeSpan(0, 1, 0));
            Driver.Manage().Timeouts().ImplicitlyWait(new TimeSpan(0, 0, 1));
            Driver.Manage().Window.Maximize();
            return Driver;
        }
 //private const int volumizingCounter = 100;
 public ChatGeneratorClass()
 {
     ChromeOptions options = new ChromeOptions();
     options.AddArguments("--incognito");
     options.AddArguments("--start-minimized");
     driver = new ChromeDriver(options);
     baseUrl = "http://pofig.livetex.ru/";
 }
		/// <summary>
		/// Get a RemoteWebDriver
		/// </summary>
		/// <param name="browser">the Browser to test on</param>
		/// <param name="languageCode">The language that the browser should accept.</param>
		/// <returns>a IWebDriver</returns>
		IWebDriver IWebDriverFactory.GetWebDriver(Browser browser, string languageCode)
		{
			//What browser to test on?s
			IWebDriver webDriver;
			switch (browser.Browserstring.ToLowerInvariant())
			{
				case "firefox":
					var firefoxProfile = new FirefoxProfile();
					firefoxProfile.SetPreference("intl.accept_languages", languageCode);
					webDriver = new FirefoxDriver(firefoxProfile);
					break;
				case "chrome":
					ChromeOptions chromeOptions = new ChromeOptions();
					chromeOptions.AddArguments("--test-type", "--disable-hang-monitor", "--new-window", "--no-sandbox", "--lang=" + languageCode);
					webDriver = new ChromeDriver(chromeOptions);
					break;
				case "internet explorer":
					webDriver = new InternetExplorerDriver(new InternetExplorerOptions { BrowserCommandLineArguments = "singleWindow=true", IntroduceInstabilityByIgnoringProtectedModeSettings = true, EnsureCleanSession = true, EnablePersistentHover = false });
					break;
				case "phantomjs":
					webDriver = new PhantomJSDriver(new PhantomJSOptions() {});
					break;
				default:
					throw new NotSupportedException("Not supported browser");
			}

			return webDriver;
		}
		private static void InitializeWebDriver() {
			switch (Configuration.BrowserType) {
				case BrowserType.Firefox:
					WebDriver = new FirefoxDriver();
					break;
				case BrowserType.InternetExplorer:
					var ieOptions = new InternetExplorerOptions {
						EnableNativeEvents = true,
						EnablePersistentHover = true,
						EnsureCleanSession = true,
						UnexpectedAlertBehavior = InternetExplorerUnexpectedAlertBehavior.Dismiss
					};

					WebDriver = new InternetExplorerDriver("./", ieOptions);
					break;
				case BrowserType.Chrome:
					var chromeOptions = new ChromeOptions();
					chromeOptions.AddArguments("test-type");

					WebDriver = new ChromeDriver("./", chromeOptions);
					break;
				default:
					throw new ArgumentException("Unknown browser type is specified!");
			}

			WebDriver.Manage().Window.Maximize();
			WebDriver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromMilliseconds(Configuration.ImplicitWaitTime));
		}
Ejemplo n.º 7
0
        public Host()
        {
            // Hack
            int retryCount = 3;
            while (true)
            {
                try
                {
                    var options = new ChromeOptions();
                    options.AddArguments("test-type");

                    var service = ChromeDriverService.CreateDefaultService(@"..\..\Scaffolding\WebDriver");
                    service.HideCommandPromptWindow = false;
                    WebDriver = new ChromeDriver(service, options);
                    WebDriver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(5));

                    Page = new Page(WebDriver);
                    Page.GotoUrl("Home");
                    break;
                }
                catch
                {
                    if (retryCount-- == 0)
                        throw;
                }
            }
        }
Ejemplo n.º 8
0
        public void GetsHeader()
        {
            var options = new OpenQA.Selenium.Chrome.ChromeOptions();

            options.AddArguments("--headless",
                                 "--disable-gpu",
                                 "windows-size=1280x1696",
                                 "--no-sandbox",
                                 "--user-data-dir=/tmp/user-data",
                                 "--hide-scrollbars",
                                 "--enable-logging",
                                 "--log-level=0",
                                 "--v=99",
                                 "--single-process",
                                 "--data-path=/tmp/data-path",
                                 "--ignore-certificate-errors",
                                 "--homedir=/tmp",
                                 "--disk-cache-dir=/tmp/cache-dir");
            options.BinaryLocation = "/var/task/chrome";

            var webdriver = new ChromeDriver(options);

            webdriver.Url = "http://www.google.com";

            string Title = webdriver.Title;

            LambdaLogger.Log($"Running test: Title for page {webdriver.Url} is: {Title}\n");

            webdriver.Quit();

            Assert.Equal("Google", Title);
        }
        public tstObject(int typNum)
        {
            brwsrType = typNum;

            switch (typNum)
            {
                //create a Chrome object
                case 1:
                {
                    var options = new ChromeOptions();

                    //set the startup options to start maximzed
                    options.AddArguments("start-maximized");

                    //start Chrome maximized
                    driver = new ChromeDriver(@Application.StartupPath, options);

                    //Wait 10 seconds for an item to appear
                    driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(4));
                    break;
                }

                //create an IE object
                case 2:
                {
                    //var options = new InternetExplorerOptions();

                    //set the startup options to start maximzed
                    //options.ToCapabilities();

                    driver = new InternetExplorerDriver(@Application.StartupPath);

                    //maximize window
                    driver.Manage().Window.Maximize();

                    //Wait 4 seconds for an item to appear
                    driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(4));

                    break;
                }
                default:
                {
                    FirefoxProfile profile = new FirefoxProfile();
                    profile.SetPreference("webdriver.firefox.profile", "cbufsusm.default");
                    profile.AcceptUntrustedCertificates = true;

                    driver = new FirefoxDriver(profile); //profile

                    //maximize window
                    driver.Manage().Window.Maximize();

                    //Wait 4 seconds for an item to appear
                    driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(4));
                    break;
                }
            }
        }
Ejemplo n.º 10
0
        static TestConsole()
        {
            var chromeOptions = new ChromeOptions();
            chromeOptions.AddArguments("--disable-web-security");
            chromeOptions.AddArguments("--start-maximized");
            WebDriver = new ChromeDriver(chromeOptions);


            //WebDriver = new InternetExplorerDriver(new InternetExplorerOptions()
            //    {
            //        IntroduceInstabilityByIgnoringProtectedModeSettings = true,
            //        UnexpectedAlertBehavior = InternetExplorerUnexpectedAlertBehavior.Ignore
            //    });
            WebDriver.Manage().Window.Maximize();
            WebDriver.Manage().Timeouts().ImplicitlyWait(new TimeSpan(VeryLongWait8));
           
         

        }
Ejemplo n.º 11
0
        public void StartDriver()
        {
            var chromeOptions = new ChromeOptions();
            chromeOptions.AddArguments("--start-maximized");
            switch (_browserName)
            {
                case BrowserNames.Chrome:

                    if (!_isUsingGrid)
                    {
                        _driver = new ChromeDriver(WebDriversDirectory, chromeOptions);
                    }
                    else
                    {
                        _capability.SetCapability(ChromeOptions.Capability, chromeOptions);
                    }
                    break;
                case BrowserNames.Firefox:
                    if (!_isUsingGrid)
                    {
                        _driver = new FirefoxDriver(new FirefoxProfile{EnableNativeEvents = true});
                        _driver.Manage().Window.Maximize();
                    }
                    break;
                case BrowserNames.InternetExplorer:
                    if (!_isUsingGrid)
                    {
                        var internetExplorerOptions = new InternetExplorerOptions
                        {
                            EnableNativeEvents = true
                        };
                        _driver = new InternetExplorerDriver(WebDriversDirectory,internetExplorerOptions);
                        _driver.Manage().Window.Maximize();
                    }
                    break;
                case BrowserNames.Safari:
                    if (!_isUsingGrid)
                    {
                        _driver = new SafariDriver();
                        _driver.Manage().Window.Maximize();
                    }
                    break;
                default:
                    throw new NotSupportedException("Unsupported browser.");
            }
            if (_isUsingGrid)
            {
                _capability.IsJavaScriptEnabled = true;
                _driver = new ExtendedRemoteWebDriver(new Uri(Configuration.HubUrl), _capability);
                _driver.Manage().Window.Maximize();
            }
            SetImplicitWait(Configuration.ImplicitWait);
        }
Ejemplo n.º 12
0
 public override IWebDriver CreateLocalDriver()
 {
     DriverType = WebDriverType.Chrome;
     var driverService = ChromeDriverService.CreateDefaultService();
     driverService.EnableVerboseLogging = true;
     driverService.HideCommandPromptWindow = true;
     var chromeOptions = new ChromeOptions();
     var capabilities = DesiredCapabilities.Chrome();
     chromeOptions.AddArguments(new string[] { "test-type" });
     capabilities.SetCapability(ChromeOptions.Capability, chromeOptions);
     return new ChromeDriver(driverService, chromeOptions);
 }
Ejemplo n.º 13
0
        public void Login()
        {
            var options = new ChromeOptions();
            DesiredCapabilities capabilities = DesiredCapabilities.Chrome();
            capabilities.SetCapability("chrome.switches", (object)("--start-maxisized"));
            options.AddArguments("--test-type", "--start-maximized");
            options.AddArguments("--test-type", "--ignore-certificate-errors");
            options.BinaryLocation = "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe";
            var driver = new ChromeDriver("C:\\Program Files (x86)\\Google\\Chrome\\Application", options);

            //var ieoptions = new InternetExplorerOptions();
            //DesiredCapabilities iecapabilities = DesiredCapabilities.InternetExplorer();
            //iecapabilities.SetCapability("internetexplorer.switches", (object)("--start-maxisized"));
            //ieoptions.AddAdditionalCapability("--test-type", "--start-maximized");
            //ieoptions.AddAdditionalCapability("--test-type", "--ignore-certificate-errors");
            //var iedriver = new InternetExplorerDriver(@"C:\Program Files (x86)\Internet Explorer");

            driver.Navigate().GoToUrl(loginurl);

            int timeout = 0;
            while (driver.FindElements(By.ClassName("logbox")).Count == 0 && timeout < 500)
            {
                Thread.Sleep(1);
                timeout++;

            }

            IWebElement element = driver.FindElement(By.ClassName("logbox"));

            IWebElement ElName = element.FindElement(By.Name("username"));
            ElName.Clear();
            ElName.SendKeys(loginName);
            IWebElement ElPassword = element.FindElement(By.Id("password"));
            ElPassword.Clear();
            ElPassword.SendKeys(loginPassword);
            IWebElement ElLogin = element.FindElement(By.Id("IBtnLogin"));
            ElLogin.Click();
        }
Ejemplo n.º 14
0
        private void CreateDriverIfNeeded()
        {
            if (null != _driver)
            {
                return;
            }
            var options = new OpenQA.Selenium.Chrome.ChromeOptions();

            options.AddArguments(new List <string>()
            {
                "headless", "no-sandbox", "disable-dev-shm-usage"
            });
            var workingDir = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
            ChromeDriverService service = ChromeDriverService.CreateDefaultService(workingDir);

            service.Port = 40785;
            _driver      = new OpenQA.Selenium.Chrome.ChromeDriver(service, options);
        }
        private static ChromeOptions CreateChromeOptions(bool leaveBrowserRunning)
        {
            try
            {
                var options = new ChromeOptions
                {
                    LeaveBrowserRunning = leaveBrowserRunning
                };

                options.AddArguments("start-maximized");

                return options;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        public ScenarioBase()
        {
            Debug.Listeners.Add(new DefaultTraceListener());
            var browser = "Chrome";

            if (browser == "Chrome")
            {
                ChromeOptions options = new ChromeOptions();
                options.AddArguments("chrome.switches", "--disable-extensions");

                ActorBase.I = new ChromeDriver(options);
                var opts = ActorBase.I.Manage();
                opts.Window.Maximize();
            }
            else if (browser == "IE")
            {
                ActorBase.I = new InternetExplorerDriver();
                var opts = ActorBase.I.Manage();
                opts.Window.Maximize();
            }
            else if (browser == "Firefox")
            {
                ActorBase.I = new FirefoxDriver();
                var opts = ActorBase.I.Manage();
                opts.Window.Maximize();
            }

            else if (browser == "Safari")
            {
                ActorBase.I = new SafariDriver();
                var opts = ActorBase.I.Manage();
                opts.Window.Maximize();
            }
            else if (browser == "PhantomJS")
            {
                var driverService = PhantomJSDriverService.CreateDefaultService();
                driverService.HideCommandPromptWindow = true;

                ActorBase.I = new PhantomJSDriver(driverService);
                var opts = ActorBase.I.Manage();
                opts.Window.Maximize();
            }
        }
Ejemplo n.º 17
0
        public IWebDriver CreateDriver()
        {
            string argumentLanguage = string.Format("--lang={0}", AppSettings.Settings.Locale);

            switch (AppSettings.Settings.Browser)
            {
            case Names.Chrome:
                OpenQA.Selenium.Chrome.ChromeOptions chromeOptions = new OpenQA.Selenium.Chrome.ChromeOptions();
                chromeOptions.AddArguments(argumentLanguage);
                return(new ChromeDriver(chromeOptions));

            case Names.FireFox:
                OpenQA.Selenium.Firefox.FirefoxOptions firefoxOptions = new OpenQA.Selenium.Firefox.FirefoxOptions();
                firefoxOptions.AddArguments(argumentLanguage);
                return(new OpenQA.Selenium.Firefox.FirefoxDriver());

            default:
                throw new ArgumentException($"Browser not yet implemented: {AppSettings.Settings.Browser}");
            }
        }
Ejemplo n.º 18
0
        public static IWebDriver CreateChromeDriver(string profileName, string path = null)
        {
            var chromeOptions = new ChromeOptions();
            if (!string.IsNullOrWhiteSpace(profileName))
            {
                var fileChars = Path.GetInvalidFileNameChars();
                var pathChars = Path.GetInvalidFileNameChars();
                var invalidChars = fileChars.Union(pathChars);

                profileName = String.Join("", profileName.Where(c => !invalidChars.Contains(c)));

                chromeOptions.AddArguments(String.Format("user-data-dir=c:\\ChromeProfiles\\{0}", profileName));
            }

            ChromeDriver Driver;

            if (!string.IsNullOrWhiteSpace(path))
            {
                //var service = ChromeDriverService.CreateDefaultService(path);
                //service.EnableVerboseLogging = true;
                //service.LogPath = "chromedriver.log";
                Driver = new ChromeDriver(path, chromeOptions);
            }
            else
            {
                //var service = ChromeDriverService.CreateDefaultService();
                //service.EnableVerboseLogging = true;
                //service.LogPath = "chromedriver.log";
                Driver = new ChromeDriver(chromeOptions);
            }

            Driver.Manage().Timeouts().SetPageLoadTimeout(new TimeSpan(0, 1, 0));
            Driver.Manage().Timeouts().ImplicitlyWait(new TimeSpan(0, 0, 1));
            Driver.Manage().Window.Maximize();
            return Driver;
        }
        /// <summary>
        /// Gets the multi browser emulator web driver.
        /// </summary>
        /// <param name="testSettings">The test settings.</param>
        /// <param name="emulator">The emulator.</param>
        /// <param name="orientation">The device orientation.</param>
        /// <param name="testOutputHelper">The test output helper.</param>
        /// <returns></returns>
        public static ITestWebDriver InitializeMultiBrowserEmulatorDriver(TestSettings testSettings, Emulator emulator, DeviceOrientation orientation, ITestOutputHelper testOutputHelper)
        {
            ScreenShotCounter = 0;
            TestOutputHelper = testOutputHelper;
            testSettings.BrowserName = emulator + " " + orientation;
            testSettings = ValidateSavePaths(testSettings);
            //string driverLocation = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData) +
            //                        "\\MultiBrowser\\Drivers\\ChromeDrivers\\2.20\\chromedriver.exe";
            string driverLocation = Path.Combine(AssemblyDirectory, "chromedriver.exe");
            driverLocation = ValidateDriverPresentOrUnblocked(WebDriverType.ChromeDriver, driverLocation);

            var driverService = ChromeDriverService.CreateDefaultService(Path.GetDirectoryName(driverLocation),
                Path.GetFileName(driverLocation));
            ValidateDriverPresentOrUnblocked(WebDriverType.ChromeDriver, driverLocation);

            var currentInstallPath = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\MultiBrowser", false) ??
                                     Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Wow6432node\MultiBrowser",
                                         false);
            string installPathValue = null;
            if (currentInstallPath != null)
            {
                installPathValue = (string) currentInstallPath.GetValue("Path");
            }
            if (installPathValue != null)
            {
                if (!installPathValue.EndsWith("\\"))
                {
                    installPathValue = installPathValue + "\\";
                }
            }

#if DEBUG
            installPathValue = @"C:\Projects\MobileEmulator\bin\Debug\x64\";
#endif
            var options = new ChromeOptions
            {
                LeaveBrowserRunning = false,
                BinaryLocation =
                    Path.Combine(installPathValue ?? @"C:\Program Files (x86)\MultiBrowser", "MultiBrowser Emulator.exe")
            };

            var emulatorSettings = MultiBrowser.GetMultiBrowserEmulators(emulator);
            if (orientation == DeviceOrientation.Portrait)
            {
                var mobileEmulationSettings = new ChromeMobileEmulationDeviceSettings
                {
                    UserAgent = emulatorSettings.DeviceUserAgent,
                    Width = emulatorSettings.DeviceWidth,
                    Height = emulatorSettings.DeviceHeight,
                    EnableTouchEvents = true,
                    PixelRatio = emulatorSettings.DevicePixelRatio
                };
                options.EnableMobileEmulation(mobileEmulationSettings);
                //options.AddAdditionalCapability("mobileEmulation", new
                //{
                //    deviceMetrics = new
                //    {
                //        width = emulatorSettings.DeviceWidth,
                //        height = emulatorSettings.DeviceHeight,
                //        pixelRatio = emulatorSettings.DevicePixelRatio
                //    },
                //    userAgent = emulatorSettings.DeviceUserAgent
                //});
            }
            else
            {
                var mobileEmulationSettings = new ChromeMobileEmulationDeviceSettings
                {
                    UserAgent = emulatorSettings.DeviceUserAgent,
                    Width = emulatorSettings.DeviceHeight,
                    Height = emulatorSettings.DeviceWidth,
                    EnableTouchEvents = true,
                    PixelRatio = emulatorSettings.DevicePixelRatio
                };
                options.EnableMobileEmulation(mobileEmulationSettings);
                

                //options.AddAdditionalCapability("mobileEmulation", new
                //{
                //    deviceMetrics = new
                //    {
                //        width = emulatorSettings.DeviceHeight,
                //        height = emulatorSettings.DeviceWidth,
                //        pixelRatio = emulatorSettings.DevicePixelRatio
                //    },
                //    userAgent = emulatorSettings.DeviceUserAgent
                //});
            }
#if DEBUG
            options.BinaryLocation = @"C:\Projects\MobileEmulator\bin\Debug\x64\MultiBrowser Emulator.exe";
#endif
            string authServerWhitelist = "auth-server-whitelist=" + testSettings.TestUri.Authority.Replace("www", "*");
            string startUrl = "startUrl=" + testSettings.TestUri.AbsoluteUri;
            string selectedEmulator = "emulator=" + emulatorSettings.EmulatorArgument;

            var argsToPass = new[]
            {
                "test-type", "start-maximized", "no-default-browser-check", "allow-no-sandbox-job",
                "disable-component-update", "disable-translate", "disable-hang-monitor", authServerWhitelist, startUrl,
                selectedEmulator
            };
            options.AddArguments(argsToPass);
            var driver = new ChromeDriver(driverService, options, testSettings.TimeoutTimeSpan);
            if (testSettings.DeleteAllCookies)
            {
                driver.Manage().Cookies.DeleteAllCookies();
            }
            driver.Manage().Timeouts().ImplicitlyWait(testSettings.TimeoutTimeSpan);
            var extendedWebDriver = new TestWebDriver(driver, testSettings, TestOutputHelper);
            TestWebDriver = extendedWebDriver;
            return extendedWebDriver;
        }
Ejemplo n.º 20
0
        private static void Main(string[] args)
        {
            //var arg0 = @"C:\temp\Dropbox\jnk\WeSellCars\"; // file path
            //var arg1 = @"C:\git\apdekock.github.io\"; //repo path
            //var arg2 = @"_posts\2015-08-04-weMineData.markdown"; //post path
            //var arg3 = @"C:\Program Files\Git\cmd\git.exe"; //git path

            try
            {
                StringBuilder listOfLines = new StringBuilder();
                var chromeOptions = new ChromeOptions();
                chromeOptions.AddArguments("-incognito");
                using (IWebDriver driver = new ChromeDriver(Path.Combine(Directory.GetCurrentDirectory(), "WebDriverServer"), chromeOptions))
                {
                    driver.Navigate().GoToUrl("http://www.wesellcars.co.za/vehicle/category/all");
                    var findElement = driver.FindElements(By.CssSelector("#main_content > div > div.vehicles.grid > div.item"));

                    foreach (var item in findElement)
                    {
                        var image = item.FindElement(By.CssSelector("a"));
                        var link = image.GetAttribute("href");
                        var lines =
                            new List<string>(item.Text.Split(new string[] { Environment.NewLine }, StringSplitOptions.None))
                            {
                                link
                            };
                        var format = string.Join(",", lines);
                        listOfLines.AppendLine(format);
                        Console.WriteLine(format);
                    }

                    driver.Quit();
                }

                var cTempCarsTxt = args[0] + @"\WeSellCars_" + DateTime.Now.ToString("dd_MM_yyyy_hh_mm_ss") + ".csv";
                var fileStream = File.Create(cTempCarsTxt);
                fileStream.Close();
                File.WriteAllText(cTempCarsTxt, listOfLines.ToString());
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }

            StringBuilder postTemplate = new StringBuilder();
            postTemplate.AppendLine("---");
            postTemplate.AppendLine("layout: post ");
            postTemplate.AppendLine("title: \"Scraping and GitSharp, and Spark lines\" ");
            postTemplate.AppendLine("date: 2016-08-07");
            postTemplate.AppendLine(
                "quote: \"If you get pulled over for speeding. Tell them your spouse has diarrhoea. — Phil Dunphy [Phil’s - osophy]\"");
            postTemplate.AppendLine("categories: scraping, auto generating post, gitsharp");
            postTemplate.AppendLine("---");
            postTemplate.AppendLine(
                string.Format(
                    "This page is a daily re-generated post (last re-generated  **{0}**), that shows the movement of prices on the [www.weSellCars.co.za](http://www.wesellcars.co.za) website.",
                    DateTime.Now));
            postTemplate.AppendLine("");
            postTemplate.AppendLine("## Why?");
            postTemplate.AppendLine("");
            postTemplate.AppendLine(
                "This post is the culmination of some side projects I've been playing around with. Scraping, looking for a way to integrate with git through C# and a challenge to use this blog (which has no back-end or support for any server side scripting) to dynamically update a post. I realise that would best be accomplished through just making new posts but I opted for an altered post as this is a tech blog, and multiple posts about car prices would not be appropriate.");
            postTemplate.AppendLine("");
            postTemplate.AppendLine("# Lessons learned");
            postTemplate.AppendLine("");
            postTemplate.AppendLine(
                "* [GitSharp](http://www.eqqon.com/index.php/GitSharp) is limited and I needed to grab the project from [github](https://github.com/henon/GitSharp) in order to use it.");
            postTemplate.AppendLine(
                "    The NuGet package kept on complaining about a **repositoryformatversion** setting in config [Core] that it required even though it was present, it still complained. So, I downloaded the source to debug the issue but then I did not encounter it. Apart from that - gitsharp did not allow me to push - and it seems the project does not have a lot of contribution activity (not criticising, just stating. I should probably take this up and contribute, especially as I would like to employ git as a file store for an application. Levering off the already refined functions coudl be a win but more on that in another post).");
            postTemplate.AppendLine(
                "* Scraping with Selenium is probably not the best way - rather employ [HttpClient](https://msdn.microsoft.com/en-us/library/system.net.http.httpclient(v=vs.118).aspx).");
            postTemplate.AppendLine(
                "* For quick, easy and painless sparklines [jQuery Sparklines](http://omnipotent.net/jquery.sparkline/#s-about)");
            postTemplate.AppendLine(
                "* No backend required, just a simple process running on a server, that commits to a repo (ghPages) gets the job done.");

            postTemplate.AppendLine("");
            var aggregateData = new AggregateData(new FileSystemLocation(args[0]));
            var dictionary = aggregateData.Aggregate();

            var html = aggregateData.GetHTML(dictionary);
            if (dictionary.Count > 0)
            {
                postTemplate.AppendLine("## The List");
            }
            postTemplate.AppendLine(html);

            // update post file
            FileInfo fi = new FileInfo(args[1] + args[2]);
            var streamWriter = fi.CreateText();
            streamWriter.WriteLine(postTemplate.ToString());

            streamWriter.Flush();
            streamWriter.Dispose();

            Repository repository = new Repository(args[1]);

            repository.Index.Add(args[1] + args[2]);
            Commit commited = repository.Commit(string.Format("Updated {0}", DateTime.Now),
                new Author("Philip de Kock", "*****@*****.**"));
            if (commited.IsValid)
            {
                string gitCommand = args[3];
                const string gitPushArgument = @"push origin";
                ProcessStartInfo psi = new ProcessStartInfo(gitCommand, gitPushArgument)
                {
                    WorkingDirectory = args[1],
                    UseShellExecute = true
                };
                Process.Start(psi);
            }
        }
 private void SetupTestChatGenerator()
 {
     ChromeOptions options = new ChromeOptions();
     options.AddArguments("--incognito");
     options.AddArguments("--start-maximized");
     driver = new ChromeDriver(options);
     baseUrl = "http://pofig.livetex.ru/";
     //verificationErrors = new StringBuilder();
 }
 private static void SetupChromeDriver()
 {
     ChromeOptions options = new ChromeOptions();
     options.AddArguments("--no-sandbox");
     Driver = new ChromeDriver(options);
 }
        public tstObject(int typNum, ref string profilePath, string baseURL)
        {
            brwsrType = typNum;

                switch (typNum)
                {
                    case 0:
                    {
                        SafariOptions opt1 = new SafariOptions();
                        opt1.CustomExtensionPath = Application.StartupPath + "\\SafariDriver2.32.0.safariextz";
                        opt1.SkipExtensionInstallation = false;

                        driver = new SafariDriver(opt1);
                        break;
                    }
                    case 1:
                    {
                        string runProfile = Application.StartupPath + "\\Firefox Profile";
                        string firebugPath = Application.StartupPath + "\\Firefox Profile\\firebug-1.9.2.xpi";
                        FirefoxProfile profile = new FirefoxProfile(runProfile);

                        //add firebug to the profile
                        //profile.AddExtension(firebugPath);

                        //add firePath to the profile
                        profile.AddExtension(firebugPath);

                        //set the webdriver_assume_untrusted_issuer to false
                        profile.SetPreference("webdriver_assume_untrusted_issuer", false);

                        //run the profile
                        driver = new FirefoxDriver(profile);

                        //maximize window
                        driver.Manage().Window.Maximize();

                        //Wait 4 seconds for an item to appear
                        driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(1));
                        break;
                    }
                    //create a Chrome object
                    case 2:
                    {
                        var options = new ChromeOptions();

                        //set the startup options to start maximzed
                        options.AddArguments("start-maximized");

                        //start Chrome maximized
                        driver = new ChromeDriver(@Application.StartupPath, options);

                        //Wait 10 seconds for an item to appear
                        driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(10));
                        break;
                    }

                    //create an IE object
                    case 3:
                    {
                        //var options = new InternetExplorerOptions();

                        //set the startup options to start maximzed
                        //options.ToCapabilities();

                        driver = new InternetExplorerDriver(@Application.StartupPath);

                        //maximize window
                        driver.Manage().Window.Maximize();

                        //Wait 4 seconds for an item to appear
                        driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(1));

                        break;
                    }
                }
        }
Ejemplo n.º 24
0
        private static IWebDriver StartChromeDriver()
        {
            Assert.That(File.Exists("chromedriver.exe"));
            var options = new ChromeOptions();
            options.AddArguments("--start-maximized");
            options.AddArguments("excludeSwitches", ("--test-type"));

            return new ChromeDriver(options);
        }
Ejemplo n.º 25
0
 private static void StartChrome()
 {
     /*
     //Это для запуска Хрома напрямую, возможно, он подхватит дефалтный профиль, а может и нет.
     //Я признаться не проверял =\
     DesiredCapabilities capabilities = DesiredCapabilities.chrome();
     capabilities.setCapability("chrome.binary", "C:\Users\Dell\AppData\Local\Google\Chrome\Application\chrome.exe");
     WebDriver driver = new ChromeDriver(capabilities);
      */
     ChromeOptions op = new ChromeOptions();
     op.AddArguments("start-maximazed");
     op.AddArguments("password_manager_enabled=false");
     op.AddArguments("user-data-dir=C:\\Users\\ruslan.lezhalkin\\AppData\\Local\\Google\\Chrome\\User Data\\Default");
     _driver = new ChromeDriver(op);
     TurnOff = false;
 }
Ejemplo n.º 26
0
        private IWebDriver DriverCreation(string DrType, bool isMassFight)
        {
            if (DrType == "Chrome")
            {
                ChromeOptions options = new ChromeOptions();
                //дизейбилм все экстеншены
                options.AddArgument("--disable-extensions");
                //Создаем и подключаем папку с профайлом
                if (Convert.ToBoolean(ReadFromFile(SettingsFile, "SystemBox")[13]))
                {
                    string path = Directory.GetCurrentDirectory();
                    string profileType = null;
                    if (isMassFight)
                        profileType = "ChromeProfileForMassFight";
                    else
                        profileType = "ChromeProfile";
                    options.AddArguments(string.Format("user-data-dir={0}/{1}", path, profileType));
                }
                //Максимайз браузер
                if (Convert.ToBoolean(ReadFromFile(SettingsFile, "SystemBox")[14]))
                {
                    options.AddArguments("start-maximized");
                }
                IWebDriver driver = new ChromeDriver(options);

                //Hide chromedriver Window
                Process[] processRunning = Process.GetProcesses();
                foreach (Process pr in processRunning)
                {
                    if (pr.ProcessName.Contains("chromedriver"))
                    {
                        hWnd = pr.MainWindowHandle.ToInt32();
                        ShowWindow(hWnd, SW_HIDE);
                        break;
                    }
                }
                Timer_OpenMySite = ToDateTime("00:53:30");
                return driver;
            }
            else
            {
                IWebDriver driver = new FirefoxDriver();
                Timer_OpenMySite = ToDateTime("00:53:30");
                return driver;
            }
        }
Ejemplo n.º 27
0
        private static IWebDriver CreateLocalDriver(ICapabilities capabilities)
        {
            // Implementation is incomplete: the capabilities are not converted to the options
            string browserType = capabilities.BrowserName;
            if (browserType == DesiredCapabilities.Firefox().BrowserName)
            {
                FirefoxDriver driver = new FirefoxDriver();
                driver.Manage().Window.Maximize();
                return driver;
            }
            if (browserType == DesiredCapabilities.InternetExplorer().BrowserName)
            {
                return new InternetExplorerDriver();
            }
            if (browserType == DesiredCapabilities.Chrome().BrowserName)
            {
                ChromeOptions options = new ChromeOptions();
                options.AddArguments("--start-maximized");
                return new ChromeDriver(options);
            }
            if (browserType == DesiredCapabilities.Safari().BrowserName)
            {
                return new SafariDriver();
            }
            if (browserType == DesiredCapabilities.PhantomJS().BrowserName)
            {
                return new PhantomJSDriver();
            }

            throw new Exception("Unrecognized browser type: " + browserType);
        }
Ejemplo n.º 28
0
 public void BeforeScenario()
 {
     var options = new ChromeOptions();
     options.AddArguments("test-type");
     Driver = new ChromeDriver(options);
 }
Ejemplo n.º 29
0
        public bool OpenBrowser(int BrowserIndex)
        {
            Trace.TraceInformation("Rudy Trace =>OpenBrowser: Set webdriver");
            string DriverTitle = System.Environment.CurrentDirectory;
            if (BrowserIndex == 0)
            {
                string ProfilePath = Environment.GetEnvironmentVariable("LocalAppData") + "\\Google\\Chrome\\User Data";
                var Options = new ChromeOptions();
                Options.AddArguments("--incognito");
                Options.AddArguments("--user-data-dir=" + ProfilePath);
                Options.AddArguments("--disable-extensions");

                driver = new ChromeDriver(Options);
                DriverTitle += "\\chromedriver.exe";
                Trace.TraceInformation("Rudy Trace =>OpenBrowser: driver = [{0}]", DriverTitle);

                App.WindowHide(DriverTitle);
            }
            else if (BrowserIndex == 1)
            {
                driver = new InternetExplorerDriver();
                DriverTitle += "\\IEDriverServer.exe";
                App.WindowHide(DriverTitle);
            }
            else if (BrowserIndex == 2)
            {
                //string firefox_path = @"C:\Program Files\Mozilla Firefox\firefox.exe";
                //FirefoxBinary binary = new FirefoxBinary(firefox_path);
                FirefoxProfile profile = new FirefoxProfile();
                profile.SetPreference("network.proxy.type", 0);
                driver = new FirefoxDriver(profile);
            }
            else
            {
                Trace.TraceInformation("Rudy Trace =>Invalid Browser Type.");
                return false;
            }

            driver.Manage().Window.Maximize();
            driver.Manage().Timeouts().SetPageLoadTimeout(TimeSpan.FromSeconds(60));
            //driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(60));
            
            return true;
        }
Ejemplo n.º 30
0
 static IWebDriver CreateInstance()
 {
     var options = new ChromeOptions();
     options.AddArguments("start-maximized", "touch-events=disabled");
     return new ChromeDriver(options);
 }