private static FirefoxOptions GetFirefoxOptions() { var firefoxProfile = new FirefoxProfile(); firefoxProfile.SetPreference("browser.download.folderList", 2); firefoxProfile.AcceptUntrustedCertificates = true; firefoxProfile.SetPreference("browser.download.dir", DownloadsDir); firefoxProfile.SetPreference("browser.download.useDownloadDir", true); firefoxProfile.SetPreference("browser.download.manager.closeWhenDone", true); firefoxProfile.SetPreference("browser.download.manager.showAlertOnComplete", false); firefoxProfile.SetPreference("browser.download.manager.alertOnEXEOpen", false); firefoxProfile.SetPreference("browser.download.manager.focusWhenStarting", false); firefoxProfile.SetPreference("browser.download.manager.useWindow", false); firefoxProfile.SetPreference("browser.download.panel.shown", false); firefoxProfile.SetPreference("pdfjs.disabled", true); firefoxProfile.SetPreference("browser.helperApps.neverAsk.saveToDisk", "application/excel;charset=utf-8;application/msword; charset=utf-8; application/x-zip-compressed; text/csv"); firefoxProfile.SetPreference("profile.assume_untrusted_issuer", true); firefoxProfile.SetPreference("profile.accept_untrusted_certs", true); firefoxProfile.SetPreference("dom.successive_dialog_time_limit", 0); var options = new FirefoxOptions { Profile = firefoxProfile }; options.AddArgument("-headless"); options.SetLoggingPreference(LogType.Driver, LogLevel.Off); options.SetLoggingPreference(LogType.Browser, LogLevel.Off); options.SetLoggingPreference(LogType.Client, LogLevel.Off); options.SetLoggingPreference(LogType.Profiler, LogLevel.Off); options.SetLoggingPreference(LogType.Server, LogLevel.Off); options.LogLevel = FirefoxDriverLogLevel.Default; return(options); }
public IWebDriverEx GetFirefoxDriver() { var mimeTypes = "image/png,image/gif,image/jpeg,image/pjpeg,application/pdf,text/csv,application/vnd.ms-excel," + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" + "application/vnd.openxmlformats-officedocument.wordprocessingml.document"; Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); var ffOptions = new FirefoxOptions(); var profile = new FirefoxProfile(); profile.SetPreference("security.sandbox.content.level", 4); profile.SetPreference("browser.download.dir", Configurator.DownloadFolder); profile.SetPreference("browser.download.folderList", 2); profile.SetPreference("browser.helperApps.alwaysAsk.force", false); profile.SetPreference("browser.download.manager.focusWhenStarting", false); profile.SetPreference("browser.download.manager.useWindow", false); profile.SetPreference("browser.download.manager.showAlertOnComplete", false); profile.SetPreference("browser.helperApps.neverAsk.saveToDisk", mimeTypes); profile.SetPreference("browser.helperApps.neverAsk.openFile", mimeTypes); profile.SetPreference("clipboardRead", "true"); ffOptions.Profile = profile; ffOptions.SetLoggingPreference(LogType.Browser, LogLevel.All); ffOptions.SetLoggingPreference(LogType.Driver, LogLevel.All); return(new FirefoxDriverEx(FirefoxDriverService.CreateDefaultService(s_executeAssemblyPath), ffOptions)); }
void CreateDriver(FirefoxOptions opt, out FirefoxDriver driver) { opt.SetLoggingPreference(LogType.Driver, LogLevel.Off); // TODO opt.SetLoggingPreference(LogType.Browser, LogLevel.Off); // TODO driver = new FirefoxDriver(service, opt, TimeSpan.FromMinutes(5)); driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(40); log.Write("driver has been created"); }
protected virtual IWebDriver _firefox() { var service = FirefoxDriverService.CreateDefaultService(Program.Options.Dir("drivers") + DriverExtension); var options = new FirefoxOptions(); service.SuppressInitialDiagnosticInformation = true; options.SetLoggingPreference(LogType.Driver, LogLevel.Off); options.SetLoggingPreference(LogType.Browser, LogLevel.Off); options.SetLoggingPreference(LogType.Client, LogLevel.Off); return(new FirefoxDriver(service, options)); }
public void Test17() { FirefoxOptions options = new FirefoxOptions(); options.SetLoggingPreference(LogType.Browser, LogLevel.Warning); driver = new FirefoxDriver(options); wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10)); LoginInternal(driver); driver.Url = "http://localhost:8080/litecart/admin/?app=catalog&doc=catalog&category_id=1"; WaitForLoad(driver, wait); var rows = driver.FindElements(By.CssSelector("form[name='catalog_form'] table.dataTable tr.row")) .Where(row => !row.FindElements(By.CssSelector("i.fa-folder-open,i.fa-folder")).Any()).ToList(); var i = 0; for (i = 0; i < rows.Count(); i++) { rows[i].FindElements(By.CssSelector("td"))[2].FindElement(By.CssSelector("a")).Click(); Thread.Sleep(400); // fails with NullReferenceException var entries = driver.Manage().Logs.GetLog(LogType.Browser); Assert.IsEmpty(entries, "logs!!!"); driver.Navigate().Back(); Thread.Sleep(400); // refresh rows rows = driver.FindElements(By.CssSelector("form[name='catalog_form'] table.dataTable tr.row")) .Where(row => !row.FindElements(By.CssSelector("i.fa-folder-open,i.fa-folder")).Any()).ToList(); } Thread.Sleep(2000); }
static void SetupDriver() { try { var ffOptions = new FirefoxOptions(); ffOptions.SetPreference("geo.enabled", false); ffOptions.SetPreference("geo.provider.use_corelocation", false); ffOptions.SetPreference("geo.prompt.testing", false); ffOptions.SetPreference("geo.prompt.testing.allow", false); if (Debugger.IsAttached) { ffOptions.SetLoggingPreference(LogType.Browser, LogLevel.All); } // Set gekodriver location. _driver = new FirefoxDriver(Directory.GetCurrentDirectory(), ffOptions); Util.FixDriverCommandExecutionDelay(_driver); } catch (Exception e) { Util.LogError(ErrorPhase.DriverInitialization, e.ToString()); } }
public override IWebDriver InitialiseForLocal() { var geckoService = FirefoxDriverService.CreateDefaultService(BuildPath); geckoService.Host = "::1"; var options = new FirefoxOptions() { AcceptInsecureCertificates = true }; if (Proxy?.HttpProxy != null) { options.Proxy = Proxy; options.AddArgument(ProxyByPassList); } if (LoggingEnabled) { options.SetLoggingPreference(LogType.Browser, LogLevel.Info); } options.SetPreference("media.navigator.streams.fake", true); options.SetPreference("media.navigator.permission.disabled", true); return(new FirefoxDriver(geckoService, options, LocalDesktopTimeout)); }
public DriverFixture(IMessageSink messageSink) { try { Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); var testWebBrowser = Environment.GetEnvironmentVariable("TestWebBrowser") ?? "Chrome"; messageSink.OnMessage(new DiagnosticMessage($"TestWebBrowser = {testWebBrowser}")); if (testWebBrowser == "Firefox") { var profiles = new FirefoxProfileManager(); var profile = profiles.GetProfile("selenium"); messageSink.OnMessage(new DiagnosticMessage("Profiles:")); foreach (var existingProfile in profiles.ExistingProfiles) { messageSink.OnMessage(new DiagnosticMessage($"Profile = {existingProfile}")); } var options = new FirefoxOptions { Profile = profile }; options.SetLoggingPreference(LogType.Browser, LogLevel.All); Driver = new FirefoxDriver(FirefoxDriverService.CreateDefaultService(Environment.CurrentDirectory), new FirefoxOptions { Profile = profile }, TimeSpan.FromSeconds(30)); } else if (testWebBrowser == "IE") { Driver = new InternetExplorerDriver(Environment.CurrentDirectory); } else if (testWebBrowser == "Chrome") { Driver = new ChromeDriver(Environment.CurrentDirectory); } Driver.Manage().Window.Position = new Point(0, 0); Driver.Manage().Window.Size = new Size(1920, 1080); Driver.Url = Environment.GetEnvironmentVariable("WebUrl") ?? "http://localhost:5000/"; messageSink.OnMessage(new DiagnosticMessage($"WebUrl = {Driver?.Url ?? "NULL"}")); Driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(10); Driver.Manage().Timeouts().AsynchronousJavaScript = TimeSpan.FromSeconds(10); Driver.Manage().Timeouts().PageLoad = TimeSpan.FromSeconds(10); Driver.FindElement(By.TagName("app-root")); } catch (Exception ex) { messageSink.OnMessage(new DiagnosticMessage($"Exception while initializing driver: {ex.Message}")); Driver?.Dispose(); } }
private static FirefoxOptions GetFirefoxOptions() { var firefoxProfile = new FirefoxProfile(); firefoxProfile.AcceptUntrustedCertificates = true; firefoxProfile.SetPreference("intl.accept_languages", ConfigInstance.Language); var options = new FirefoxOptions { Profile = firefoxProfile }; options.SetLoggingPreference(LogType.Driver, LogLevel.Off); options.SetLoggingPreference(LogType.Browser, LogLevel.Off); options.LogLevel = FirefoxDriverLogLevel.Default; options.AddArgument("-headless"); return(options); }
public override IWebDriver CreateWebDriver() { Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); string driverFileName = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? "geckodriver.exe" : "geckodriver"; var service = FirefoxDriverService.CreateDefaultService(Directory.GetCurrentDirectory(), driverFileName); service.SuppressInitialDiagnosticInformation = true; var firefoxOptions = new FirefoxOptions { PageLoadStrategy = PageLoadStrategy.Eager, }; firefoxOptions.AddArgument("-headless"); var firefoxProfile = new FirefoxProfile(); firefoxProfile.SetPreference("media.volume_scale", "0.0"); firefoxOptions.Profile = firefoxProfile; firefoxOptions.LogLevel = FirefoxDriverLogLevel.Fatal; firefoxOptions.SetLoggingPreference(LogType.Client, LogLevel.Off); firefoxOptions.SetLoggingPreference(LogType.Browser, LogLevel.Off); firefoxOptions.SetLoggingPreference(LogType.Driver, LogLevel.Off); firefoxOptions.SetLoggingPreference(LogType.Profiler, LogLevel.Off); firefoxOptions.SetLoggingPreference(LogType.Server, LogLevel.Off); service.HideCommandPromptWindow = true; IWebDriver driver; try { driver = new FirefoxDriver(service, firefoxOptions); } catch (WebDriverException) { return(CreateWebDriver()); } FixDriverCommandExecutionDelay(driver); return(driver); }
public static IWebDriver GetWebDriver(bool withEvents) { Func <IWebDriver> webDriverFunc; DriverOptions options; switch (Config.Browser) { case BrowserType.Chrome: options = new ChromeOptions(); // ((ChromeOptions) options).AddArgument("no-sandbox"); // ((ChromeOptions) options).AddArgument("headless"); options.SetLoggingPreference(LogType.Browser, LogLevel.All); webDriverFunc = () => { var driver = new ChromeDriver((ChromeOptions)options); return(driver); }; break; case BrowserType.Firefox: options = new FirefoxOptions { AcceptInsecureCertificates = true }; options.SetLoggingPreference(LogType.Browser, LogLevel.All); webDriverFunc = () => new FirefoxDriver((FirefoxOptions)options); break; default: throw new Exception($"Browser {Config.Browser} is not supported"); } if (Config.Selenoid) { options.AddAdditionalOption("selenoid:options", new Dictionary <string, object> { ["enableLog"] = true, ["enableVnc"] = false, ["enableVideo"] = false, }); options.AddAdditionalOption("env", new Dictionary <string, object> { ["VERBOSE"] = true, }); webDriverFunc = () => new RemoteWebDriverWithLogs(new Uri(Config.SelenoidHubUrl), options); } var webDriver = webDriverFunc.Invoke(); webDriver.Manage().Window.Size = new Size(1600, 800); return((withEvents) ? GetEventFiringWebDriver(webDriver) : webDriver); }
public IWebDriver GetFirefoxDriver() { var mimeTypes = "image/png,image/gif,image/jpeg,image/pjpeg,application/pdf,text/csv,application/vnd.ms-excel," + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" + "application/vnd.openxmlformats-officedocument.wordprocessingml.document"; var ffOptions = new FirefoxOptions(); var profile = new FirefoxProfile(); profile.SetPreference("browser.download.folderList", 2); profile.SetPreference("browser.helperApps.neverAsk.saveToDisk", mimeTypes); profile.SetPreference("browser.helperApps.neverAsk.openFile", mimeTypes); ffOptions.Profile = profile; ffOptions.SetLoggingPreference(LogType.Browser, LogLevel.All); ffOptions.SetLoggingPreference(LogType.Driver, LogLevel.All); new DriverManager().SetUpDriver(new FirefoxConfig()); return(new FirefoxDriver(ffOptions)); }
private void SetupDriverOptions(BrowserType browser, DriverOptions options, LogLevel logLevel) { switch (browser) { case BrowserType.Chrome: if (options != null && options is ChromeOptions) { _chromeOpts = options as ChromeOptions; } _chromeOpts.SetLoggingPreference(LogType.Browser, logLevel); break; case BrowserType.Edge: if (options != null && options is EdgeOptions) { _edgeOpts = options as EdgeOptions; } _edgeOpts.SetLoggingPreference(LogType.Browser, logLevel); break; case BrowserType.Firefox: if (options != null && options is FirefoxOptions) { _firefoxOpts = options as FirefoxOptions; } _firefoxOpts.SetLoggingPreference(LogType.Browser, logLevel); break; case BrowserType.IE: if (options != null && options is InternetExplorerOptions) { _ieOpts = options as InternetExplorerOptions; } _ieOpts.SetLoggingPreference(LogType.Browser, logLevel); break; case BrowserType.Phantomjs: if (options != null && options is PhantomJSOptions) { _phantomJsOpts = options as PhantomJSOptions; } _phantomJsOpts.SetLoggingPreference(LogType.Browser, logLevel); break; case BrowserType.Safari: if (options != null && options is SafariOptions) { _safariOpts = options as SafariOptions; } _safariOpts.SetLoggingPreference(LogType.Browser, logLevel); break; } }
/// <summary> /// CreateBrowser returns an IWebBrowser object to be used by page object classes. /// </summary> /// <param name="browserType"></param> /// <returns></returns> public static IWebDriver CreateBrowser(BrowserType browserType) { switch (browserType) { case BrowserType.Chrome: ChromeOptions cOptions = new ChromeOptions(); cOptions.AddArgument("ignore-certificate-errors"); cOptions.AddArgument("window-size=1900x1080"); cOptions.AddArgument("start-maximized"); // set logging to "Severe" and the event will add anything from the js console to the allure report cOptions.SetLoggingPreference(LogType.Browser, LogLevel.All); // cOptions.SetLoggingPreference(LogType.Driver, LogLevel.All); driver.Value = new ChromeDriver(cOptions); driver.Value.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(20); firingDriver.Value = new EventFiringWebDriver(driver.Value); firingDriver.Value.ExceptionThrown += _firingDriver_ExceptionThrown; firingDriver.Value.Navigated += _firingDriver_Navigated; return(firingDriver.Value); case BrowserType.Firefox: FirefoxOptions options = new FirefoxOptions(); options.AddArgument("ignore-certificate-errors"); // logging does not appear to work for Firefox... options.SetLoggingPreference(LogType.Browser, LogLevel.All); driver.Value = new FirefoxDriver(options); driver.Value.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(20); firingDriver.Value = new EventFiringWebDriver(driver.Value); firingDriver.Value.ExceptionThrown += _firingDriver_ExceptionThrown;; firingDriver.Value.Navigated += _firingDriver_Navigated; return(firingDriver.Value); case BrowserType.Edge: return(new EdgeDriver()); case BrowserType.GalaxyA51: ChromeOptions chromeOptions = new ChromeOptions(); chromeOptions.AddAdditionalChromeOption("androidPackage", "com.android.chrome"); chromeOptions.AddAdditionalChromeOption("androidDeviceSerial", ""); driver.Value = new ChromeDriver(chromeOptions); driver.Value.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(20); firingDriver.Value = new EventFiringWebDriver(driver.Value); firingDriver.Value.ExceptionThrown += _firingDriver_ExceptionThrown; firingDriver.Value.Navigated += _firingDriver_Navigated; return(firingDriver.Value); default: throw new ArgumentOutOfRangeException(nameof(browserType), browserType, null); } }
public WebDriverConfiguration GetBrowser(Constants.BrowserType browser, string browserPath) { WebDriverConfiguration webDriverConfiguration = new WebDriverConfigurationFactory().Create(); switch (browser) { case Constants.BrowserType.Chrome: var chromeOptions = new ChromeOptions(); chromeOptions.SetLoggingPreference(LogType.Browser, LogLevel.All); chromeOptions.AddArgument("--ignore-certificate-errors"); //chromeOptions.AddUserProfilePreference("profile.managed_default_content_settings.images", 2); chromeOptions.AddUserProfilePreference("profile.default_content_settings.state.flash", 0); webDriverConfiguration.WebDriver = new ChromeDriver(AppDomain.CurrentDomain.BaseDirectory + browserPath, chromeOptions); break; case Constants.BrowserType.FireFox: webDriverConfiguration.FireFoxService = FirefoxDriverService.CreateDefaultService(AppDomain.CurrentDomain.BaseDirectory + browserPath, "geckodriver.exe"); FirefoxOptions firefoxOptions = new FirefoxOptions(); firefoxOptions.SetLoggingPreference(LogType.Browser, LogLevel.All); firefoxOptions.AddAdditionalCapability("acceptInsecureCerts", true, true); webDriverConfiguration.WebDriver = new FirefoxDriver(webDriverConfiguration.FireFoxService, firefoxOptions, TimeSpan.FromSeconds(180)); break; case Constants.BrowserType.InternetExplorer: var internetExplorerOptions = new InternetExplorerOptions(); internetExplorerOptions.AddAdditionalCapability(CapabilityType.AcceptSslCertificates, true); internetExplorerOptions.EnsureCleanSession = true; webDriverConfiguration.WebDriver = new InternetExplorerDriver(AppDomain.CurrentDomain.BaseDirectory + browserPath, internetExplorerOptions); break; default: { string errorMsg = FormattableString.Invariant( $"Browser type: {browser}. Try and use BrowserStack by setting UseBrowserStack to true in app.config and run the StartBrowserStackLocal.ps1 before running the test."); throw new NotSupportedException(errorMsg); } } return(webDriverConfiguration); }
public void Initialize(BrowserType browser) { Browser = browser; ChromeOptions chromeOptions = new ChromeOptions(); switch (Browser) { case BrowserType.Chrome: //ChromeOptions chromeOptions = new ChromeOptions(); chromeOptions.SetLoggingPreference(LogType.Browser, LogLevel.All); chromeOptions.AddArgument("--disable-notifications"); _webDriver = new ChromeDriver(chromeOptions); WebDriverEventFiring(); break; case BrowserType.Firefox: FirefoxOptions options = new FirefoxOptions(); options.SetLoggingPreference(LogType.Browser, LogLevel.All); _webDriver = new FirefoxDriver(); WebDriverEventFiring(); break; case BrowserType.MobileEmulator: chromeOptions.EnableMobileEmulation("iPhone 6"); _webDriver = new ChromeDriver(chromeOptions); WebDriverEventFiring(); break; } if (Browser != BrowserType.MobileChrome) { driver.Manage().Window.Maximize(); driver.Manage().Timeouts().PageLoad = TimeSpan.FromSeconds(30); driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(5); } else { driver.Manage().Timeouts().PageLoad = TimeSpan.FromSeconds(50); driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(50); } //BaseURL = "http://localhost:8080/web/home.html"; BaseURL = "http://localhost:2122/web/home.html"; }
protected IWebDriver InitializeFireFoxDriver(IWebDriverSetup setup) { var fireFoxOptions = new FirefoxOptions(); if (setup.BrowserArgs.Any()) { foreach (string arg in setup.BrowserArgs) { fireFoxOptions.AddArgument(arg); } } fireFoxOptions.SetLoggingPreference(setup.WebDriverLogLevel.LogType, setup.WebDriverLogLevel.LogLevel); fireFoxOptions.AcceptInsecureCertificates = setup.AcceptInsecureCertificates; return(GetDriver <FirefoxDriver>(fireFoxOptions, setup)); }
public IWebDriver Create() { var driverService = FirefoxDriverService.CreateDefaultService(); driverService.FirefoxBinaryPath = FirefoxBinaryPath; driverService.HideCommandPromptWindow = true; driverService.SuppressInitialDiagnosticInformation = true; var options = new FirefoxOptions(); options.SetPreference("javascript.enabled", true); options.SetLoggingPreference(LogType.Browser, LogLevel.Warning); options.SetPreference( "general.useragent.override", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:54.0) Gecko/20100101 Firefox/54.0 Selenium/3.4"); return(new FirefoxDriver(driverService, options, CommandTimeout)); }
private (DriverService, IWebDriver) GetFirefoxDriver(ILogger logger) { var options = new FirefoxOptions(); options.SetLoggingPreference(LogType.Browser, SeleniumLogLevel.All); options.AddArguments(new List <string>(_arguments.BrowserArgs) { "--incognito", "--headless", }); logger.LogInformation($"Starting Firefox with args: {string.Join(' ', options.ToCapabilities())}"); var driverService = FirefoxDriverService.CreateDefaultService(); return(driverService, new FirefoxDriver(driverService, options, _arguments.Timeout)); }
private void Init() { FirefoxOptions options = new FirefoxOptions(); var driverService = FirefoxDriverService.CreateDefaultService(); driverService.HideCommandPromptWindow = true; //options.AddArgument("--start-maximized"); //options.AddArgument("--auth-server-whitelist"); //options.AddArguments("--disable-extensions"); options.AddArgument("--ignore-certificate-errors"); options.AddArgument("--ignore-ssl-errors"); options.AddArgument("--system-developer-mode"); options.AddArgument("--no-first-run"); options.SetLoggingPreference(LogType.Driver, LogLevel.All); //options.AddAdditionalCapability("useAutomationExtension", false); //chromeOptions.AddArguments("--disk-cache-size=0"); //options.AddArgument("--user-data-dir=" + m_chr_user_data_dir); #if !DEBUG options.AddArguments("--headless"); options.AddArguments("--user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.117 Safari/537.36"); options.AddArguments("--disable-plugins-discovery"); //options.AddArguments("--profile-directory=Default"); //options.AddArguments("--no-sandbox"); //options.AddArguments("--incognito"); //options.AddArguments("--disable-gpu"); //options.AddArguments("--no-first-run"); //options.AddArguments("--ignore-certificate-errors"); //options.AddArguments("--start-maximized"); //options.AddArguments("disable-infobars"); //options.AddAdditionalCapability("acceptInsecureCerts", true, true); #endif FirefoxDriver = new FirefoxDriver(driverService, options, TimeSpan.FromSeconds(DEFAULT_TIMEOUT_PAGELOAD)); FirefoxDriver.Manage().Window.Position = new Point(0, 0); FirefoxDriver.Manage().Window.Size = new Size(1200, 900); FirefoxDriver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(5); JSE = (IJavaScriptExecutor)FirefoxDriver; Wait = new WebDriverWait(FirefoxDriver, TimeSpan.FromSeconds(180)); Wait.IgnoreExceptionTypes(typeof(StaleElementReferenceException)); Wait.IgnoreExceptionTypes(typeof(NoSuchElementException)); }
/// <summary> /// TODO: Set as Private /// </summary> /// <param name="locale"></param> /// <returns></returns> public IWebDriver GetFirefoxDriver(string locale = "", FirefoxProfile profile = null) { Console.Write("Loading FireFox Driver"); if (locale == "") { locale = "en_US"; } IWebDriver d; if (profile == null) { profile = new FirefoxProfile(); profile.AcceptUntrustedCertificates = true; profile.AssumeUntrustedCertificateIssuer = true; } if (Settings.isLocal) { FirefoxOptions options = new FirefoxOptions(); options.Profile = profile; options.AddAdditionalCapability(CapabilityType.AcceptSslCertificates, true); options.AddAdditionalCapability(CapabilityType.HasNativeEvents, true); options.AddAdditionalCapability("acceptSslCerts", true); options.AddAdditionalCapability("acceptInsecureCerts", true); options.SetLoggingPreference(LogType.Browser.ToString(), LogLevel.All); options.LogLevel = FirefoxDriverLogLevel.Trace; FirefoxDriverService service = FirefoxDriverService.CreateDefaultService(URL.driver); d = new FirefoxDriver(service, options, TimeSpan.FromMinutes(60)); return(d); } else { DesiredCapabilities desiredCapabilities = DesiredCapabilities.Firefox(); desiredCapabilities.SetCapability("firefox_profile", profile); d = new RemoteWebDriverPlus(new Uri(URL.seleniumHub), desiredCapabilities); return(d); } }
private static IWebDriver CreateDriver(BrowserType browserType) { switch (browserType) { case BrowserType.Chrome: var chromeOptions = new ChromeOptions(); chromeOptions.AddArgument("--headless"); chromeOptions.AddArgument("--window-size=1920,1080"); chromeOptions.SetLoggingPreference(LogType.Browser, LogLevel.All); return(new ChromeDriver(GetDriverLocation(browserType), chromeOptions)); case BrowserType.Firefox: var firefoxOptions = new FirefoxOptions(); firefoxOptions.AddArgument("-headless"); firefoxOptions.AddArgument("--window-size=1920,1080"); firefoxOptions.SetLoggingPreference(LogType.Browser, LogLevel.All); return(new FirefoxDriver(GetDriverLocation(browserType), firefoxOptions)); default: throw new NotSupportedException($"Browser type '{browserType}' is not supported."); } }
static void Main(string[] args) { #region init browser var firefoxOptions = new FirefoxOptions(); firefoxOptions.SetLoggingPreference(LogType.Browser, LogLevel.Off); firefoxOptions.SetLoggingPreference(LogType.Server, LogLevel.Off); firefoxOptions.SetLoggingPreference(LogType.Client, LogLevel.Off); firefoxOptions.SetLoggingPreference(LogType.Profiler, LogLevel.Off); firefoxOptions.SetLoggingPreference(LogType.Driver, LogLevel.Off); firefoxOptions.LogLevel = FirefoxDriverLogLevel.Error; firefoxOptions.AcceptInsecureCertificates = true; firefoxOptions.AddArguments("-purgecaches", "-private", "--disable-gpu", "--disable-direct-write", "--disable-display-color-calibration", "--allow-http-screen-capture", "--disable-accelerated-2d-canvas"); Driver = new FirefoxDriver("./", firefoxOptions, TimeSpan.FromSeconds(120)); Driver.Manage().Timeouts().PageLoad = TimeSpan.FromSeconds(120); Driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(5); #endregion Driver.Navigate().GoToUrl("https://www.swisslife.ch/de/private.html/"); /* Find the element inside the driver safe without exception */ var labelToScroll = Driver.FindElementFirstOrDefault(By.CssSelector("h3.a-heading--style-italic"), 5); Console.WriteLine(labelToScroll.Text); /* Scroll to the element and take a screenshot of the element */ var img = Driver.GetElementScreenshot(labelToScroll); Console.WriteLine($"The screenshot is {img.Height} pixels height"); /* Find all elementS inside the parent safe without exception */ var labels = Driver.FindElementsOrDefault(By.TagName("h3")); Console.WriteLine($"{labels.Count} labels of h3 found"); /* Real example, accept the disclaimer, if it exists */ var disclaimerButton = Driver.FindElementFirstOrDefault(By.CssSelector("[class*='cookie-disclaimer']>button"), 1); if (disclaimerButton != null) { disclaimerButton.Click(); } /* Search a not existing element inside the parent, should by null after 5 seconds */ var notFound = Driver.FindElementFirstOrDefault(By.TagName("h99"), 5); Console.WriteLine($"Element h99 is {notFound}"); /* The position from top */ var y = Driver.GetScrollPosition(); Console.WriteLine($"You are {y} pixels from top"); /* Navigate relative */ Driver.NavigateToPath("/de/private/kontakt-service/persoenliche-services.html"); Console.WriteLine($"Your are here: {Driver.Title}"); /* Resize the browser */ Driver.SetMobileSize(); /* Make a screenshot of the whole browser and safe it to bin/testresults folder */ Driver.MakeScreenshot("swisslife.png"); /* Set Selenium flag */ Driver.SetSeleniumFlag(); /* Execute a JavaScript */ Driver.ExecuteScript("alert('FunkyBDD');"); #region console handling Console.WriteLine(" "); Console.WriteLine("Press enter to terminate..."); Console.ReadLine(); #endregion #region teardown browser Driver.Close(); Driver.Dispose(); Driver.Quit(); #endregion }
public void Download(string path, int lcount, int currentpos = 0) { try { var ps = new ProjectSpecific(); int i = currentpos; foreach (ClipModel model in clipjson) { foreach (clips clip in model.clips) { int retry = 0; i++; current++; string[] url = Regex.Split(clip.thumbnails.medium, "-preview"); url[0] = url[0] + ".mp4"; if (!Regex.IsMatch(url[0], "offset")) { Retry: var htmldoc = new HtmlDocument(); FirefoxOptions op = new FirefoxOptions(); op.AddArgument("--headless"); op.SetLoggingPreference("driver", LogLevel.Off); IWebDriver driver = new FirefoxDriver(op); driver.Navigate().GoToUrl("https://clips.twitch.tv/embed?clip=" + clip.slug); driver.Manage().Timeouts().PageLoad = TimeSpan.FromSeconds(60); htmldoc.LoadHtml(driver.PageSource); driver.Quit(); retry++; var node = htmldoc.DocumentNode.SelectSingleNode("//div[@class='clips-embed-page tw-c-background-base tw-full-height']/div[@class='video-player']/div[@class='tw-absolute tw-bottom-0 tw-left-0 tw-overflow-hidden tw-right-0 tw-top-0 video-player__container']/video/@src"); if (retry == 3) { ps.ConsoleRedX($"Failed to download clip {current}/{totalclips} - {clipjson.First().clips.First().title}", false); clips[] carray = { clipjson.First().clips.First() }; if (File.Exists($@".\{clipjson.First().clips.First().broadcaster.name}-faileddump.json")) { Failedclipsjson = JsonConvert.DeserializeObject <List <ClipModel> >(File.ReadAllText($@".\{clipjson.First().clips.First().broadcaster.name}-faileddump.json")); } Failedclipsjson.Add(new ClipModel { clips = carray, _cursor = "" }); File.WriteAllText($@".\{clipjson.First().clips.First().broadcaster.name}-faileddump.json", JsonConvert.SerializeObject(Failedclipsjson)); clipjson.First().clips = clipjson.First().clips.Where((source, index) => index != 0).ToArray(); goto End; } if (node == null) { goto Retry; } url[0] = node.Attributes[2].Value; } WebClient wc = new WebClient(); string clean = null; //temp fix to remove illegal characters foreach (var c in (new string(Path.GetInvalidFileNameChars()) + new string(Path.GetInvalidPathChars()))) { if ($"{clip.broadcaster.name}_{clip.title}_{clip.created_at}".Contains(c.ToString())) { clean = $"{clip.broadcaster.name}_{clip.title}_{clip.created_at}".Replace(c, '-'); } } clean = clean.Replace('<', '-').Replace('>', '-').Replace('?', '-').Replace('|', '-').Replace('*', '-').Replace(':', '-').Replace('"', '_').Replace('\'', '-').Replace('\\', '_').Replace('/', '_').Trim(); wc.DownloadFile(new Uri(url[0]), path + '\\' + clean + ".mp4"); ps.ConsoleGreenCheck($"Downloaded clip {i}/{lcount} - {clip.title} - {clip.url.Split('?')[0]}"); End: if (model.clips.Length != 0) { model.clips = model.clips.Where((source, index) => index != 0).ToArray(); } else { break; } } } if (clipjson.Count != 0) { clipjson.RemoveAt(0); } else { ps.ConsoleGreenCheck("Finished downloading!"); return; } } catch (Exception ex) { try { var ps = new ProjectSpecific(); var dt = DateTime.Now; ps.ConsoleRedX($"Oh no! An error occured! Please screenshot this and provide the crash log located at ({Directory.GetCurrentDirectory() })\\CrashReport_{dt.ToString().Replace(':', '-').Replace('/', '-')}.txt)" + $"to masamesa via submitting an issue on github!\r\n" + ex, true); File.WriteAllText($@".\CrashReport_{dt.ToString().Replace(':', '-').Replace('/', '-')}.txt", ex.ToString()); //error handling if for whatever reason the clipjson.clips were to be empty. start: if (clipjson.Count != 0 && clipjson.First().clips.Length != 0) { ps.ConsoleRedX($"Failed to download clip {current}/{totalclips} - {clipjson.First().clips.First().title}", false); clips[] carray = { clipjson.First().clips.First() }; if (File.Exists($@".\{clipjson.First().clips.First().broadcaster.name}-faileddump.json")) { Failedclipsjson = JsonConvert.DeserializeObject <List <ClipModel> >(File.ReadAllText($@".\{clipjson.First().clips.First().broadcaster.name}-faileddump.json")); } Failedclipsjson.Add(new ClipModel { clips = carray, _cursor = "" }); File.WriteAllText($@".\{clipjson.First().clips.First().broadcaster.name}-faileddump.json", JsonConvert.SerializeObject(Failedclipsjson)); clipjson.First().clips = clipjson.First().clips.Where((source, index) => index != 0).ToArray(); ps.ConsoleGreenCheck($"Recovered! Using backup {Directory.GetCurrentDirectory() + '\\' + clipjson.First().clips.First().broadcaster.name}-backup.json..."); if (!File.Exists($@".\{clipjson.First().clips.First().broadcaster.name}-backup.json")) { File.Create($@".\{clipjson.First().clips.First().broadcaster.name}-backup.json").Close(); } File.WriteAllText($@".\{clipjson.First().clips.First().broadcaster.name}-backup.json", JsonConvert.SerializeObject(clipjson)); Download(path, totalclips, current); } else if (clipjson.Count != 0 && clipjson.First().clips.Length == 0) { clipjson.RemoveAt(0); goto start; } else { ps.ConsoleRedX("Failed to save and restart! Something went very wrong...", false); } } catch (Exception err) { var ps = new ProjectSpecific(); var dt = DateTime.Now; ps.ConsoleRedX($"EMERGENCY BACKUP MADE.\r\nPLEASE TRY AGAIN AND SUBMIT AN ISSUE ON GITHUB WITH A SCREENSHOT AND THE CRASH REPORT LOCATED AT ({Directory.GetCurrentDirectory() })\\CrashReport_{dt.ToString().Replace(':', '-').Replace('/', '-')}.txt), THIS IS VERY ABNORMAL.\r\n{err}", true); File.WriteAllText($@".\CrashReport_{dt.ToString().Replace(':', '-').Replace('/', '-')}.txt", err.ToString() + "\r\nEx:\r\n" + ex.ToString()); ps.ConsoleGreenCheck($"Recovered! Using backup {Directory.GetCurrentDirectory() + '\\' + clipjson.First().clips.First().broadcaster.name}-backup.json..."); if (!File.Exists($@".\{clipjson.First().clips.First().broadcaster.name}-backup.json")) { File.Create($@".\{clipjson.First().clips.First().broadcaster.name}-backup.json").Close(); } File.WriteAllText($@".\{clipjson.First().clips.First().broadcaster.name}-backup.json", JsonConvert.SerializeObject(clipjson)); } } }
static void Main() { #region init browser var firefoxOptions = new FirefoxOptions(); firefoxOptions.SetLoggingPreference(LogType.Browser, LogLevel.Off); firefoxOptions.SetLoggingPreference(LogType.Server, LogLevel.Off); firefoxOptions.SetLoggingPreference(LogType.Client, LogLevel.Off); firefoxOptions.SetLoggingPreference(LogType.Profiler, LogLevel.Off); firefoxOptions.SetLoggingPreference(LogType.Driver, LogLevel.Off); firefoxOptions.LogLevel = FirefoxDriverLogLevel.Error; firefoxOptions.AcceptInsecureCertificates = true; firefoxOptions.AddArguments("-purgecaches", "-private", "--disable-gpu", "--disable-direct-write", "--disable-display-color-calibration", "--allow-http-screen-capture", "--disable-accelerated-2d-canvas"); Driver = new FirefoxDriver("./", firefoxOptions, TimeSpan.FromSeconds(120)); Driver.Manage().Timeouts().PageLoad = TimeSpan.FromSeconds(120); Driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(5); #endregion Driver.Navigate().GoToUrl("https://www.swisslife.ch/de/private.html/"); var parent = Driver.FindElement(By.TagName("body")); /* Sometimes you need the wrapped driver of the parent */ IWebDriver wrappedDriver = parent.GetDriver(); Console.WriteLine($"The current window has the title '{wrappedDriver.Title}'"); /* Find the element inside the parent element safe without exception */ var labelToScroll = parent.FindElementFirstOrDefault(By.CssSelector("h3.a-heading--style-italic"), 5); Console.WriteLine(labelToScroll.Text); /* Test ScrollTo() */ if (labelToScroll != null) { labelToScroll.ScrollTo(); Console.WriteLine("Scrolled to this label"); } /* Find all elementS inside the parent safe without exception */ var labels = parent.FindElementsOrDefault(By.TagName("h3")); Console.WriteLine($"{labels.Count} labels of h3 found"); /* Real example, accept the disclaimer, if it exists */ var disclaimerButton = parent.FindElementFirstOrDefault(By.CssSelector("[class*='cookie-disclaimer']>button"), 1); if (disclaimerButton != null) { disclaimerButton.Click(); } /* Search a not existing element inside the parent, should by null after 5 seconds */ var notFound = parent.FindElementFirstOrDefault(By.TagName("h99"), 5); Console.WriteLine($"Element h99 is {notFound}"); #region console handling Console.WriteLine(" "); Console.WriteLine("Press enter to terminate..."); Console.ReadLine(); #endregion #region teardown browser Driver.Close(); Driver.Dispose(); Driver.Quit(); #endregion }
public static IWebDriver Build(string browser, bool runTestsRemotely, string driverVersion = "Latest") { IWebDriver webDriver; const string nodeURI = "http://23.100.236.70:4446/wd/hub"; switch (browser.ToLower()) { case "chrome": var chromeOptions = new ChromeOptions(); var chromeBrowser = new ChromeBrowser(); chromeBrowser.StartIfNotRunning(); chromeOptions.DebuggerAddress = $"localhost:{chromeBrowser.DebuggingPort}"; chromeOptions.SetLoggingPreference(LogType.Browser, LogLevel.All); new DriverManager().SetUpDriver(new ChromeConfig(), driverVersion); webDriver = runTestsRemotely ? new RemoteWebDriver(new Uri(nodeURI), chromeOptions) : new ChromeDriver(chromeOptions); break; case "chrome-incognito-ignore-certificate": var chromeIncogAndIgnCertErrsOptions = new ChromeOptions(); chromeIncogAndIgnCertErrsOptions.AddArguments("--incognito", "--ignore-certificate-errors"); chromeIncogAndIgnCertErrsOptions.SetLoggingPreference(LogType.Browser, LogLevel.All); new DriverManager().SetUpDriver(new ChromeConfig(), driverVersion); webDriver = runTestsRemotely ? new RemoteWebDriver(new Uri(nodeURI), chromeIncogAndIgnCertErrsOptions) : new ChromeDriver(chromeIncogAndIgnCertErrsOptions); break; case "chrome-headless": var chromeHeadlessOptions = new ChromeOptions(); chromeHeadlessOptions.AddArgument("--headless"); chromeHeadlessOptions.SetLoggingPreference(LogType.Browser, LogLevel.All); new DriverManager().SetUpDriver(new ChromeConfig(), driverVersion); webDriver = runTestsRemotely ? new RemoteWebDriver(new Uri(nodeURI), chromeHeadlessOptions) : new ChromeDriver(chromeHeadlessOptions); break; case "firefox": var firefoxOptions = new FirefoxOptions(); firefoxOptions.SetLoggingPreference(LogType.Browser, LogLevel.All); new DriverManager().SetUpDriver(new FirefoxConfig(), driverVersion); webDriver = runTestsRemotely ? new RemoteWebDriver(new Uri(nodeURI), firefoxOptions) : new FirefoxDriver(firefoxOptions); break; case "edge": var edgeOptions = new EdgeOptions(); edgeOptions.SetLoggingPreference(LogType.Browser, LogLevel.All); new DriverManager().SetUpDriver(new EdgeConfig(), driverVersion); webDriver = runTestsRemotely ? new RemoteWebDriver(new Uri(nodeURI), edgeOptions) : new EdgeDriver(edgeOptions); break; case "safari": var safariOptions = new SafariOptions(); safariOptions.SetLoggingPreference(LogType.Browser, LogLevel.All); webDriver = runTestsRemotely ? new RemoteWebDriver(new Uri(nodeURI), safariOptions) : new SafariDriver(safariOptions); break; default: throw new ApplicationException($"The functionality to run scripts for {browser} driver has not been implemented"); } webDriver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(WaitUtils.defaultImplicitWait); webDriver.Manage().Window.Maximize(); return(webDriver); }