Provides a way to access Firefox to run tests.
When the FirefoxDriver object has been instantiated the browser will load. The test can then navigate to the URL under test and start your test.

In the case of the FirefoxDriver, you can specify a named profile to be used, or you can let the driver create a temporary, anonymous profile. A custom extension allowing the driver to communicate to the browser will be installed into the profile.

Inheritance: OpenQA.Selenium.Remote.RemoteWebDriver, ITakesScreenshot
 public static IWebDriver GetDriver(string driver, Devices device)
 {
     DeviceModel model = Device.Get(device);
     IWebDriver webDriver;
     switch (driver.ToLower())
     {
         case "safari":
             webDriver = new SafariDriver();
             break;
         case "chrome":
             webDriver = new ChromeDriver();
             break;
         case "ie":
             webDriver = new InternetExplorerDriver();
             break;
         //case "firefox":
         default:
             var profile = new FirefoxProfile();
             profile.SetPreference("general.useragent.override", model.UserAgent);
             webDriver = new FirefoxDriver(profile);
             webDriver.Manage().Window.Size = model.ScreenSize;
             break;
     }
     return webDriver;
 }
        public void Attack2_NonProtected()
        {
            IWebDriver driver = new FirefoxDriver();
            driver.Navigate().GoToUrl("http://localhost/LU.ENGI3675.Project04/StudentInputUNSAFE.aspx");

            IWebElement query = driver.FindElement(By.Name("fullNameUS"));

            query.SendKeys("a','2.1'); update students * set gpa = 4.0; --");
            query = driver.FindElement(By.Name("GPAUS"));
            query.SendKeys("0");
            query = driver.FindElement(By.Name("button"));
            query.Click();
            System.Threading.Thread.Sleep(1000);

            List<LU.ENGI3675.Proj04.App_Code.Students> students =
                LU.ENGI3675.Proj04.App_Code.DatabaseAccess.Read();

            foreach (LU.ENGI3675.Proj04.App_Code.Students temp in students)
            {
                Assert.IsTrue((double)temp.GPA == 4);   //if any of them aren't 4.0, injection failed
                Debug.Write((string)temp.Name);
                Debug.Write(" ");
                Debug.WriteLine((double)temp.GPA);
            }
            driver.Quit();
        }
        static void Main(string[] args)
        {
            IWebDriver driver = new FirefoxDriver();
            const int idInicio = 0;
            const int idFim = 1000;

            int id = idInicio;
            String url = "http://fcv.matheusacademico.com.br/Aluno/frmAlunoAlteracao.asp?id=";

            driver.Navigate().GoToUrl(url + id);
            driver.Manage().Window.Maximize();

            using (System.IO.StreamWriter file = new System.IO.StreamWriter(@"c:\AllStudents1.txt", true))
            {
                while (id < idFim)
                {
                    driver.Navigate().GoToUrl(url + id);
                    IWebElement nome = driver.FindElement(By.Id("txtNome"));
                    IWebElement email = driver.FindElement(By.Id("txtmail_maior"));

                    if (nome.GetAttribute("value").ToString() != "")
                        file.WriteLine(id.ToString() + " - " + nome.GetAttribute("value").ToString() + " - " + email.GetAttribute("value").ToString());
                    id++;
                }
            }
        }
        // GET: RunSystemAdministrator
        public ActionResult RunSalesExecutive()
        {
            IWebDriver driver = new FirefoxDriver();
            driver.Navigate().GoToUrl("http://localhost:4601/");
            var emp = _employeeService
                             .Queryable()
                             .Where(x => x.DepartmentRoleId == 10)
                             .FirstOrDefault ();
            emp.EmployeeLogin = _employeeLoginService
                                .Queryable()
                                .Where(x => x.EmployeeId == emp.EmployeeId)
                                .FirstOrDefault();
            IWebElement UserName = driver.FindElement(By.Name("UserName"));
            IWebElement Password = driver.FindElement(By.Name("Password"));
            var loginButton = driver.FindElement(By.XPath("/html/body/div/div/div/section/form/button"));

            UserName.SendKeys(emp.EmployeeLogin.UserName);
            Password.SendKeys(emp.EmployeeLogin.Password);
            loginButton.Click();

            Timer timer = new Timer(1000);
            timer.Start();

            timer.Stop();
            return View();
        }
        private static IWebDriver CreateWebDriver()
        {
            IWebDriver driver = null;

            var type = ConfigurationManager.AppSettings["WebDriver"];
            switch (type)
            {
                case "Firefox":
                    {
                        var firefoxProfile = new FirefoxProfile
                        {
                            AcceptUntrustedCertificates = true,
                            EnableNativeEvents = true
                        };
                        driver = new FirefoxDriver(firefoxProfile);

                        break;
                    }
                case "Chrome":
                case "InternetExplorer":
                    // TODO
                    break;
                default:
                    throw new NotSupportedException();
            }
            return driver;
        }
 public IWebDriver CreateWebDriver()
 {
     var driver = new FirefoxDriver();
     driver.Manage().Window.Maximize();
     driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(3));
     return driver;
 }
        public void Add_Tweet_FindNewTweetInNewsfeed()
        {
            firefox = new FirefoxDriver();
            firefox.Navigate().GoToUrl("http://*****:*****@mail.com");
            //firefox.FindElement(By.Id("inputPassword")).SendKeys("123");
            //firefox.FindElement(By.Id("submit")).Click();
            //firefox.FindElement(By.Id("login")).Click();

            //log in page
            firefox.FindElement(By.Id("inputEmail")).SendKeys("*****@*****.**");
            firefox.FindElement(By.Id("inputPassword")).SendKeys("123");
            firefox.FindElement(By.Id("login")).Click();

            firefox.FindElement(By.Name("Body")).Click();
            firefox.FindElement(By.Name("Body")).SendKeys("test Tweet");

            firefox.FindElement(By.Id("tweetbutton")).Click();
            firefox.FindElement(By.Id("home")).Click();

            string tweetMessage = firefox.FindElement(By.TagName("h5")).Text;

            Assert.IsTrue(tweetMessage == "test Tweet");
        }
Exemple #8
0
        public void CreateExamSchemaTest()
        {
            IWebDriver driver = new FirefoxDriver();
            driver.Navigate().GoToUrl("http://dev.chd.miraclestudios.us/probo-php/admin/apps/backend/site/login");
            driver.FindElement(By.Id("UserLoginForm_username")).Clear();
            driver.FindElement(By.Id("UserLoginForm_username")).SendKeys("owner");
            driver.FindElement(By.Id("UserLoginForm_password")).Clear();
            driver.FindElement(By.Id("UserLoginForm_password")).SendKeys("ZFmS!H3*wJ2~^S_zx");
            driver.FindElement(By.Id("login-content-button")).Click();

            System.Threading.Thread.Sleep(2000);

            driver.FindElement(By.LinkText("Manage Examination")).Click();
            driver.FindElement(By.LinkText("Manage Exam Scheme")).Click();
            System.Threading.Thread.Sleep(2000);
            driver.FindElement(By.LinkText("Create Exam Scheme")).Click();
            System.Threading.Thread.Sleep(5000);
            Random rnd = new Random();

            new SelectElement(driver.FindElement(By.Id("PrbExamScheme_exam_category_id"))).SelectByText("Food Safety");

            new SelectElement(driver.FindElement(By.Id("levelid"))).SelectByText("Project Manager3610");
            driver.FindElement(By.Id("PrbExamScheme_scheme_name")).Clear();
            driver.FindElement(By.Id("PrbExamScheme_scheme_name")).SendKeys("ISO softengineering" + rnd.Next(1, 1000));
            driver.FindElement(By.Name("yt0")).Click();

            string URL = driver.Url;
            Assert.AreNotEqual("http://dev.chd.miraclestudios.us/probo-php/admin/apps/backend/probo/competencyDomain/view/id/", URL.Substring(0, 89));
            driver.Quit();
        }
Exemple #9
0
 public static RemoteWebDriver GetBrowser()
 {
     //return new PhantomJSDriver(); // faster
     var result = new FirefoxDriver(); // easier debugging
     result.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(5));
     return result;
 }
        /// <summary>
        /// Starts the specified browser.
        /// </summary>
        /// <param name="browser">The browser.</param>
        /// <exception cref="System.NotSupportedException">When driver not supported</exception>
        public void Start(string browser)
        {
            switch (browser)
            {
                case "Firefox":
                    Handle = new FirefoxDriver(this.FirefoxProfile);
                    break;
                case "FirefoxPortable":

                    var profile = this.FirefoxProfile;
                    var firefoxBinary = new FirefoxBinary(BaseConfiguration.FirefoxPath);
                    Handle = new FirefoxDriver(firefoxBinary, profile);
                    break;
                case "InternetExplorer":
                    var options = new InternetExplorerOptions
                    {
                        EnsureCleanSession = true,
                    };
                    Handle = new InternetExplorerDriver(@"Drivers\", options);
                    break;
                case "Chrome":
                    Handle = new ChromeDriver(@"Drivers\");
                    break;
                default:
                    throw new NotSupportedException(
                        string.Format(CultureInfo.CurrentCulture, "Driver {0} is not supported", browser));
            }

            Handle.Manage().Window.Maximize();
        }
Exemple #11
0
        /// <summary>
        /// Test all links on the Krossover home page
        /// </summary>
        public void testHomePage(FirefoxDriver driver)
        {
            string homePage = "http://www.krossover.com/";
            driver.Navigate().GoToUrl(homePage);
            Thread.Sleep(1000);

            //find all links on the page
            IList<IWebElement> links = driver.FindElementsByTagName("a");

            //loop through all of the links on the page
            foreach (IWebElement link in links)
            {
                try
                {
                    //check if any of the links return a 404
                    link.SendKeys(Keys.Control + Keys.Enter);
                    driver.SwitchTo().Window(driver.WindowHandles.Last());

                    driver.FindElementByXPath("//div[contains(@class, '404')]");
                    log(link.GetAttribute("href") + " is broken.  Returned 404");

                    driver.SwitchTo().Window(driver.WindowHandles.First());
                }
                catch
                {
                    //continue to the next link
                    continue;
                }

            }
            driver.Quit(); //kill the driver
        }
        public void Attack1_Protected()
        {
            IWebDriver driver = new FirefoxDriver();
            driver.Navigate().GoToUrl("http://localhost/LU.ENGI3675.Project04/StudentInput.aspx");

            IWebElement query = driver.FindElement(By.Name("fullName"));

            query.SendKeys("a','2.1'); update students * set gpa = 4.0; --");
            query = driver.FindElement(By.Name("GPA"));
            query.SendKeys("3");
            query = driver.FindElement(By.Name("button"));
            query.Click();
            System.Threading.Thread.Sleep(5000);

            List<LU.ENGI3675.Proj04.App_Code.Students> students =
                LU.ENGI3675.Proj04.App_Code.DatabaseAccess.Read();
            bool allfour = true;
            foreach (LU.ENGI3675.Proj04.App_Code.Students temp in students)
            {
                if (temp.GPA < 4.0) allfour = false;
                Debug.Write((string)temp.Name);
                Debug.Write(" ");
                Debug.WriteLine((double)temp.GPA);
            }
            Assert.IsFalse(allfour);    //if they aren't all 4.0 gpa, then protected against SQL injection
            driver.Quit();
        }
Exemple #13
0
 public static void BeforeScenario()
 {
     Trace.WriteLine("Launching web browser");
     IWebDriver driver = new FirefoxDriver();
     Trace.WriteLine("Finished launching web browser");
     FeatureContext.Current.SetWebDriver(driver);
 }
Exemple #14
0
		public static IWebDriver StartDriver (string browserType)
		{
			Trace.WriteLine("Start browser: '" + browserType + "'");

			IWebDriver driver = null;
			switch (browserType)
			{
				case "ie":
					{
						driver = new InternetExplorerDriver("Drivers");
						break;
					}
				case "firefox":
					{
						FirefoxProfile firefoxProfile = new FirefoxProfile();
						firefoxProfile.EnableNativeEvents = true;
						firefoxProfile.AcceptUntrustedCertificates = true;

						driver = new FirefoxDriver(firefoxProfile);
						break;
					}
				case "chrome":
					{
						ChromeOptions chromeOptions = new ChromeOptions();
						chromeOptions.AddArgument("--disable-keep-alive");

						driver = new ChromeDriver("Drivers", chromeOptions);
						break;
					}
			}

			driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(3));
			driver.Manage().Window.Maximize();
			return driver;
		}
Exemple #15
0
 public void PostToBlog()
 {
     IWebDriver browser = new FirefoxDriver();
     browser.Navigate().GoToUrl("http://tumblr.com/login");
     IWebElement email = browser.FindElement(By.Id("signup_determine_email"));
     email.SendKeys("*****@*****.**");
     IWebElement verifyButton = browser.FindElement(By.Id("signup_forms_submit"));
     verifyButton.Click();
     browser.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(5));
     IWebElement password = browser.FindElement(By.Id("signup_password"));
     password.SendKeys("******");
     IWebElement loginButton = browser.FindElement(By.Id("signup_forms_submit"));
     loginButton.Click();
     IWebElement textIcon = browser.FindElement(By.ClassName("icon_post_text"));
     textIcon.Click();
     IWebElement postTitle = browser.FindElement(By.ClassName("editor-plaintext"));
     postTitle.SendKeys("c# selenium");
     IWebElement postBody = browser.FindElement(By.ClassName("editor-richtext"));
     postBody.SendKeys("this is a c# with selenium test");
     IWebElement createPost = browser.FindElement(By.ClassName("create_post_button"));
     createPost.Click();
     //TearDown
     IWebElement postSettings = browser.FindElement(By.ClassName("post_control_menu"));
     postSettings.Click();
     IWebElement postDelete = browser.FindElement(By.ClassName("delete"));
     postDelete.Click();
     IWebElement okButton = browser.FindElement(By.ClassName("btn_1"));
     okButton.Click();
     IWebElement accountButton = browser.FindElement(By.ClassName("icon_user_settings"));
     browser.Close();
 }
Exemple #16
0
        static void Main(string[] args)
        {
            IWebDriver driver = new FirefoxDriver();

            driver.Navigate().GoToUrl(@"http://www.weibo.com");

            WebDriverWait waitPageOpen = new WebDriverWait(driver, TimeSpan.FromSeconds(60));
            IWebElement inpt_username = waitPageOpen.Until<IWebElement>((d) => { return d.FindElement(By.Name("username")); });
            waitPageOpen.Until((d) => { return inpt_username.Displayed; });
            inpt_username.SendKeys(@"*****@*****.**");

            IWebElement inpt_pwd = driver.FindElement(By.Name("password"));
            inpt_pwd.SendKeys(@"kodakpdc2000");

            IWebElement btn_login = driver.FindElement(By.ClassName("W_btn_g"));
            btn_login.Click();

            waitPageOpen.Until((d)=>{return d.Title.StartsWith("我的首页");});

            //IList<IWebElement> personInfos = driver.FindElements(By.ClassName("user_atten"));
            //if (personInfos.Count == 1)
            //{ personInfos[0].FindElement(By.PartialLinkText("粉丝")).Click(); }

            IWebElement temp = driver.FindElement(By.PartialLinkText("粉丝"));
            temp.Click();

            Console.Read();
        }
Exemple #17
0
        public void LogonTest()
        {
            IWebDriver driver = new FirefoxDriver();
            //IWebDriver driver = new ChromeDriver();
            //IWebDriver driver = new InternetExplorerDriver();
            driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(10));

            //ChromeDriver driver = new ChromeDriver();
            string homepageURL = "https://*****:*****@gmail.com", "F5ft2mz0_");

            //verify the user is logged in
            Assert.IsTrue(indexPageObject.CheckAuthentication(true));

            //driver.Close();
        }
 public void FirefoxStartup()
 {
     FirefoxDriver dr = new FirefoxDriver();
     dr.Manage().Window.Maximize();
     dr.Navigate().GoToUrl(url);
     dr.Quit();
 }
Exemple #19
0
        public void Execute(IDictionary<string, object> variables, Dictionary<string, ObjectInfo> library, string[] parameters)
        {
            return;
            var browserType = (variables.ContainsKey("Browser") && (string)variables["Browser"] != "") ? (string)variables["Browser"] : parameters[0];

            Console.WriteLine("OpenBrowser.Execute");
            IWebDriver browser = null;

            if (browserType == "Firefox")
            {
                browser = new FirefoxDriver();
            }
            else if (browserType == "IE")
            {
                browser = new InternetExplorerDriver(@"C:\projects\poc\pcg.qa.webtester\pcg.qa.webtester\Tools\");
            }
            else
            {
                throw new TestingException("Non Supported Browser!");
            }

            if (browser != null)
            {
                variables["BrowserInstance"] = browser;
            }
            else
            {
                throw new TestingException("Browser Instance not found!");
            }
        }
        /// <summary>
        /// Test form submission on Krossover basketball page
        /// </summary>
        public void testBasketballPage(FirefoxDriver driver)
        {
            //variables to enter in form
            string page = "http://www.krossover.com/basketball/";
            string name = "Jóhn Dóe"; //international character testing
            string teamName = "Test Team";
            string city = "New York";
            string state = "NY";
            string sport = "Football";
            string gender = "Male";
            string email = "*****@*****.**";
            string phone = "123-456-789";
            string day = "Friday";

            //fill out all the fields
            driver.Navigate().GoToUrl(page);
            driver.FindElementByName("Field1").SendKeys(name);
            driver.FindElementByName("Field2").SendKeys(teamName);
            driver.FindElementByName("Field3").SendKeys(city);
            driver.FindElementByName("Field4").SendKeys(state);
            driver.FindElementByName("Field6").FindElement(By.XPath(".//option[contains(text(),'" + sport + "')]")).Click();
            driver.FindElementByName("Field7").FindElement(By.XPath(".//option[contains(text(),'" + gender + "')]")).Click();
            driver.FindElementByName("Field9").SendKeys(email);
            driver.FindElementByName("Field11").SendKeys(phone);
            driver.FindElementByName("Field14").FindElement(By.XPath(".//option[contains(text(),'" + day + "')]")).Click();

            driver.FindElementByName("saveForm").Click(); //submit the form

            /*verify the form submission was actually generated by querying the db
             * if so, test passes
             * else, test fails
            */
            driver.Quit();
        }
        public static IWebDriver GetConfigBrowser(string browserName)
        {
            string AppRoot = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
            string strDriverPath = null;
            IWebDriver webDriver = null;
            if (browserName.Equals("Firefox", StringComparison.InvariantCultureIgnoreCase))
            {
                webDriver = new FirefoxDriver();
            }
            else if (browserName.Equals("chrome", StringComparison.InvariantCultureIgnoreCase))
            {
                strDriverPath = Path.Combine(AppRoot, @"CodedUITests\Drivers\chromedriver_win32");
                webDriver = new ChromeDriver(strDriverPath);

            }
            else if (browserName.Equals("IE", StringComparison.InvariantCultureIgnoreCase))
            {
                InternetExplorerOptions options = new InternetExplorerOptions()
                {
                    EnableNativeEvents = true,
                    IgnoreZoomLevel = true
                };
                strDriverPath = Path.Combine(AppRoot, @"CodedUITests\Drivers\IEDriverServer_Win32_2.44.0");
                webDriver = new InternetExplorerDriver(strDriverPath, options, TimeSpan.FromMinutes(3.0));
            }
            if (webDriver == null)
                throw new Exception("must configure browsername in aap.config");
            else
                return webDriver;
        }
Exemple #22
0
        public void SimpleNavigationTest()
        {
            // 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.
            IWebDriver driver = new FirefoxDriver();

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

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

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

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

            // Google's search is rendered dynamically with JavaScript.
            // Wait for the page to load, timeout after 10 seconds
            WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
            wait.Until((d) => { return d.Title.ToLower().StartsWith("cheese"); });

            //Close the browser
            driver.Quit();
        }
        public static IWebDriver GetDriver(DriverType typeOfDriver)
        {
            IWebDriver browser;
            switch (typeOfDriver)
            {
                // NOTE REMOTE DRIVER IS NOT SUPPORTED
                case DriverType.Chrome:
                    ChromeOptions co = new ChromeOptions();
                    browser = new ChromeDriver();
                    break;
                case DriverType.IE:
                    InternetExplorerOptions ieo = new InternetExplorerOptions();
                    browser = new InternetExplorerDriver();
                    break;
                case DriverType.Firefox:    
                default:
                    FirefoxProfile ffp = new FirefoxProfile();
                    ffp.AcceptUntrustedCertificates = true;
                    ffp.Port = 8181;

                    browser = new FirefoxDriver(ffp);
                    break;
            }
            return browser;
        }
 public void OneCanLoginStackoverflow()
 {
     IWebDriver driver = new FirefoxDriver();
     StartPage startPage = new StartPage(driver);
     String title = startPage.OpenPage().SignIn().Login(USERNAME, PASSWORD).GetPageTitle();
     Console.WriteLine(title);
 }
        public void SingUp_TestUser_FindNameInHelloString()
        {
            firefox = new FirefoxDriver();
            firefox.Navigate().GoToUrl("http://*****:*****@mail.com");
            firefox.FindElement(By.Id("inputPassword")).SendKeys("123");
            firefox.FindElement(By.Id("submit")).Click();
            firefox.FindElement(By.Id("login")).Click();

            //log in page
            firefox.FindElement(By.Id("inputEmail")).SendKeys("*****@*****.**");
            firefox.FindElement(By.Id("inputPassword")).SendKeys("123");
            firefox.FindElement(By.Id("login")).Click();

            firefox.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(10));
            string helloString = firefox.FindElement(By.Id("helloString")).Text;
            string result = "Hello, testFirstName testLastName";

            //delete test user
            firefox.Navigate().GoToUrl("http://localhost:57336/User/UsersProfile");
            firefox.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(10));
            firefox.FindElement(By.Id("deleteProfile")).Click();

            Assert.IsTrue(result == helloString);
        }
        public List<FootballItem> Parse() {
            List<FootballItem> res = new List<FootballItem>();

            IWebDriver driver = new FirefoxDriver();

            driver.Navigate().GoToUrl("https://www.marathonbet.com/su/popular/Football/?menu=true#");
            ReadOnlyCollection<IWebElement> main = driver.FindElements(By.ClassName("sport-category-container"));
            Debug.Assert(main.Count==1);
            ReadOnlyCollection<IWebElement> containers = main[0].FindElements(By.ClassName("category-container"));
            foreach (IWebElement container in containers) {
                ReadOnlyCollection<IWebElement> tables = container.FindElements(By.ClassName("foot-market"));
                Debug.Assert(tables.Count==1);
                ReadOnlyCollection<IWebElement> tbodys = tables[0].FindElements(By.XPath(".//tbody[@data-event-name]"));
                ParseTBody(tbodys, res);
            }

            /*
            WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
            wait.Until((d) => { return d.Title.ToLower().StartsWith("cheese"); });
            */
            driver.Close();
            driver.Quit();

            return res;
        }
        static void Main(string[] args)
        {
            FirefoxDriver driver = new FirefoxDriver();
            //напрямую в гугл не пробиться - осядем на вводе капчи изза подозрительной деятельности
            //потому пойдем через яндекс
            driver.Url = "https://ya.ru";
            
            //ищем гугл
            driver.FindElementByXPath("//*[@id='text']").SendKeys("Google" + Keys.Enter);

            //теперь переходим по ссылке от яндекса
            driver.Url = driver.FindElementByPartialLinkText("google.ru").Text.ToString();

            driver.Url = "https://www.google.ru/#newwindow=1&q=zerg+rush";

            do
            {

                try
                {
                    driver.FindElementByXPath(".//*[@class='zr_zergling_container']").Click();
                }
                catch
                {
                    //если зерглинга еще нет
                }
            } while (true); //TODO: заменить на число из статистики

            Console.ReadKey();
            driver.Quit();
        }
Exemple #28
0
        public IWebDriver LoadFirefoxDriver(bool headless = false)
        {
            var driverService = FirefoxDriverService.CreateDefaultService(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location));

            try
            {
                driverService.HideCommandPromptWindow = true;
                driverService.Host = "::1";

                var options = new FirefoxOptions();
                options.AddArgument("--disable-extensions");
                options.AddArgument("--disable-popup-blocking");
                options.AddArgument("--window-size=1920,1080");
                options.AddArguments("--disable-infobars");

                if (headless == true)
                {
                    options.AddArgument("headless");
                }

                var driver = new OpenQA.Selenium.Firefox.FirefoxDriver(driverService, options);
                driver.Manage().Window.Maximize();
                return(driver);
            }
            catch (WebDriverException we)
            {
                throw new WebDriverException(we.Message);
            }
        }
 public static void EnsureDriverIsInitialised()
 {
     if (CurrentDriver == null)
     {
       CurrentDriver = new FirefoxDriver();
     }
 }
        public void WindowProcess_Demo2()
        {
            var articleName = "[小北De编程手记] : Lesson 02 - Selenium For C# 之 核心对象";

            _output.WriteLine("Step 01 : 启动浏览器并打开Lesson 01 - Selenium For C#");
            IWebDriver driver = new FirefoxDriver();
            driver.Url = "http://www.cnblogs.com/NorthAlan/p/5155915.html";

            _output.WriteLine("Step 02 : 点击链接打开新页面。");
            var lnkArticle02 = driver.FindElement(By.LinkText(articleName));
            lnkArticle02.Click();

            _output.WriteLine("Step 03 : 根据标题获取新页面的句柄。");
            var oldWinHandle = driver.CurrentWindowHandle;
            foreach (var winHandle in driver.WindowHandles)
            {
                driver.SwitchTo().Window(winHandle);
                if (driver.Title.Contains(articleName))
                {
                   break;
                }
            }

            _output.WriteLine("Step 04 : 验证新页面标题是否正确。");
            var articleTitle = driver.FindElement(By.Id("cb_post_title_url"));
            Assert.Equal<string>(articleName, articleTitle.Text);

            _output.WriteLine("Step 05 : 关闭浏览器。");
            driver.Quit();

        }
Exemple #31
0
        public void injectionAttack()
        {
            FirefoxDriver ffox = new FirefoxDriver();

            ffox.Navigate().GoToUrl("localhost:58374/safeinsert.aspx");
            ffox.FindElementById("sname").SendKeys("Bart Simpson',4);delete from students where name='Bart Simpson';update students set gpa = 4;--");
            ffox.FindElementById("sgpa").SendKeys("2.0");
            ffox.FindElementById("InsertStudent").Click();

            DataTable results = ServerConn.MyQuery("SELECT * FROM students");

            bool InjectionFailed = false;

            foreach (DataRow d in results.Rows)
            {
                if (d.ItemArray[1].Equals("Bart Simpson',4);delete from students where name='Bart Simpson';update students set gpa = 4;--"))
                    InjectionFailed = true;
            }

            Assert.IsTrue(InjectionFailed, "Error: Safe insert did not prevent the SQL injection");

            ffox.Navigate().GoToUrl("localhost:58374/unsafeinsert.aspx");
            ffox.FindElementById("sname").SendKeys("Bart Simpson',4);delete from students where name='Bart Simpson';update students set gpa = 4;--");
            ffox.FindElementById("sgpa").SendKeys("4.0");
            ffox.FindElementById("InsertStudent").Click();

            results = ServerConn.MyQuery("SELECT * FROM students");
            foreach (DataRow d in results.Rows)
            {
                Assert.AreEqual((float) 4, (float) d.ItemArray[2], "Error: Student {0} does not have a GPA of 4", d.ItemArray[1].ToString());
                Assert.AreNotEqual("Bart Simpson", d.ItemArray[1].ToString(), "Error you didn't cover your tracks!");
            }
        }
Exemple #32
0
    static void Main()
    {
        using (var driver = new OpenQA.Selenium.Firefox.FirefoxDriver(AppDomain.CurrentDomain.BaseDirectory))
        {
            driver.Navigate().GoToUrl("https://www.bing.com/");
            driver.FindElement(By.Id("sb_form_q")).SendKeys("Selenium WebDriver");
            driver.FindElement(By.Id("sb_form_go")).Click();

            Console.WriteLine("OK");
            Console.ReadKey(intercept: true);
        }
    }
        public void BrowserAutoComplete(LoginCard card)
        {
            string browser     = IdentifyDefaultBrowser();
            string target_name = "";

            OpenQA.Selenium.IWebDriver driver = null;

            switch (browser)
            {
            case "Firefox": { driver = new OpenQA.Selenium.Firefox.FirefoxDriver(); target_name = "geckodriver"; break; }

            case "Chrome": { driver = new OpenQA.Selenium.Chrome.ChromeDriver(); target_name = "chromedriver"; break; }

            case "Edge": { driver = new OpenQA.Selenium.Edge.EdgeDriver(); target_name = "MicrosoftWebDriver"; break; }

            default: { driver = new OpenQA.Selenium.IE.InternetExplorerDriver(); target_name = "IEDriverServer"; break; }
            }

            try
            {
                driver.Navigate().GoToUrl(card.SiteURL);
                driver.FindElement(By.Name(card.LogElem)).Clear();
                driver.FindElement(By.Name(card.LogElem)).SendKeys(card.Login);
                driver.FindElement(By.Name(card.PassElem)).Clear();
                driver.FindElement(By.Name(card.PassElem)).SendKeys(card.Password);
            }
            catch
            { }

            try
            {
                System.Diagnostics.Process[] local_procs = System.Diagnostics.Process.GetProcesses();
                System.Diagnostics.Process   target_proc = local_procs.First(p => p.ProcessName == target_name);
                target_proc.Kill();
            }
            catch { }
        }
Exemple #34
0
        private QA.IWebDriver InitWebDriver(string cache_dir, bool loadImage = true, string useragent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.131 Safari/537.36")
        {
            if (!Directory.Exists(cache_dir))
            {
                Directory.CreateDirectory(cache_dir);
            }
            QA.IWebDriver theDriver = null;
            switch (this.browser)
            {
            case Browsers.IE:
            {
                InternetExplorerDriverService driverService = InternetExplorerDriverService.CreateDefaultService(Application.StartupPath + "\\Drivers\\");
                driverService.HideCommandPromptWindow = true;
                driverService.SuppressInitialDiagnosticInformation = true;
                ds = driverService;
                QA.IE.InternetExplorerOptions _ieOptions = new QA.IE.InternetExplorerOptions();
                _ieOptions.IntroduceInstabilityByIgnoringProtectedModeSettings = true;
                theDriver  = new QA.IE.InternetExplorerDriver(driverService, _ieOptions);
                _ProcessID = driverService.ProcessId;
            }; break;

            case Browsers.Chrome:
            {
                ChromeDriverService driverService = ChromeDriverService.CreateDefaultService(Application.StartupPath + "\\Drivers\\");
                driverService.Port = new Random().Next(1000, 2000);
                driverService.HideCommandPromptWindow = true;
                driverService.SuppressInitialDiagnosticInformation = true;
                ds = driverService;
                ChromeOptions options = new QA.Chrome.ChromeOptions();
                options.AddArgument("--window-size=" + Screen.PrimaryScreen.WorkingArea.Width + "x" + Screen.PrimaryScreen.WorkingArea.Height);
                options.AddArgument("--disable-gpu");
                options.AddArgument("--disable-extensions");
                options.AddArgument("--no-sandbox");
                options.AddArgument("--disable-dev-shm-usage");
                options.AddArgument("--disable-java");
                options.AddArgument("--user-agent=" + useragent);
                options.AddArgument(@"--user-data-dir=" + cache_dir);
                if (loadImage == false)
                {
                    options.AddUserProfilePreference("profile.managed_default_content_settings.images", 2);        //不加载图片
                }
                theDriver  = new QA.Chrome.ChromeDriver(driverService, options, TimeSpan.FromSeconds(240));
                _ProcessID = driverService.ProcessId;
            };
                break;

            case Browsers.Firefox:
            {
                var driverService = FirefoxDriverService.CreateDefaultService(Application.StartupPath + "\\Drivers\\");
                driverService.HideCommandPromptWindow = true;
                driverService.SuppressInitialDiagnosticInformation = true;
                ds = driverService;
                FirefoxProfile profile = new FirefoxProfile();
                if (loadImage == false)
                {
                    profile.SetPreference("permissions.default.image", 2);
                    // 关掉flash
                    profile.SetPreference("dom.ipc.plugins.enabled.libflashplayer.so", false);
                }
                FirefoxOptions options = new FirefoxOptions();
                options.Profile = profile;
                theDriver       = new QA.Firefox.FirefoxDriver(driverService, options, TimeSpan.FromMinutes(240));
                _ProcessID      = driverService.ProcessId;
            };
                break;

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

            default:
            {
                QA.IE.InternetExplorerOptions _ieOptions = new QA.IE.InternetExplorerOptions();
                _ieOptions.IntroduceInstabilityByIgnoringProtectedModeSettings = true;
                theDriver = new QA.IE.InternetExplorerDriver(_ieOptions);
            };
                break;
            }
            //theDriver.Manage().Window.Maximize();
            return(theDriver);
        }
        static void Main(string[] args)
        {
            try
            {
                string baseUrl = "http://www.webmetrics.com";
                if (args.Length >= 1)
                {
                    baseUrl = args[0];
                }

                string filename;
                if (args.Length >= 2)
                {
                    filename = args[1];
                }
                else
                {
                    Uri uri = new Uri(baseUrl);
                    filename = uri.Host.Replace(".", "-") + @".har";
                }

                // Uncomment to enable SSL support
                // Fiddler.CONFIG.IgnoreServerCertErrors = true;
                // FiddlerApplication.Prefs.SetBoolPref("fiddler.network.streaming.abortifclientaborts", true);

                // Varibale to store the list of items downloaded
                var sessions = new List <Fiddler.Session>();

                // As each HTTP item is downloaded add it to our list.
                // We will export this list later.
                Fiddler.FiddlerApplication.AfterSessionComplete += delegate(Fiddler.Session oS)
                {
                    Monitor.Enter(sessions);
                    sessions.Add(oS);
                    Monitor.Exit(sessions);
                };

                // As each HTTP item is downloaded add it to our list.
                // We will export this list later.
                Fiddler.FiddlerApplication.BeforeRequest += delegate(Fiddler.Session oS)
                {
                    if (!new Regex(baseUrl).IsMatch(oS.fullUrl))
                    {
                        oS.utilCreateResponseAndBypassServer();
                        oS.responseCode = 200;
                    }
                };

                // Start Fiddler on port 8877.
                // Register as the system wide proxy.
                Fiddler.FiddlerApplication.Startup(8877, FiddlerCoreStartupFlags.Default);

                /////////////////////////////////////////////////
                // Begin selenium test
                /////////////////////////////////////////////////

                var webDriver = new OpenQA.Selenium.Firefox.FirefoxDriver();
                var selenium  = new Selenium.WebDriverBackedSelenium(webDriver, baseUrl);

                selenium.Start();
                selenium.Open(baseUrl);
                selenium.WaitForPageToLoad("30000");
                selenium.Stop();

                /////////////////////////////////////////////////
                // End selenium test
                /////////////////////////////////////////////////

                // Load the HAR file exporter (this only has to be done once per process).
                // The following DLL was downloaded from:
                // https://www.fiddler2.com/dl/FiddlerCore-BasicFormats.zip
                // It is currently only loadable with FiddlerCode 2.2.9.9.
                String path = Path.Combine(Path.GetDirectoryName
                                               (Assembly.GetExecutingAssembly().Location), @"FiddlerCore-BasicFormats.dll");
                FiddlerApplication.oTranscoders.ImportTranscoders(path);

                // Export fiddler sessions to HAR file
                Monitor.Enter(sessions);
                var oExportOptions = new Dictionary <string, object>();
                oExportOptions.Add("Filename", filename);
                bool fiddler = Fiddler.FiddlerApplication.DoExport("HTTPArchive v1.2", sessions.ToArray(), oExportOptions, null);
                sessions.Clear();
                Monitor.Exit(sessions);
            }
            finally
            {
                // Shutdown fiddler, this removes Fiddler as the system proxy.
                Fiddler.FiddlerApplication.Shutdown();
                Thread.Sleep(500);
            }
        }
Exemple #36
0
 /// <summary>
 /// Initializes a new instance of the <see cref="FirefoxWebElement"/> class.
 /// </summary>
 /// <param name="parentDriver">The <see cref="FirefoxDriver"/> instance hosting this element.</param>
 /// <param name="id">The ID assigned to the element.</param>
 public FirefoxWebElement(FirefoxDriver parentDriver, string id)
     : base(parentDriver, id)
 {
 }
Exemple #37
0
 private FirefoxDriver(FirefoxBinary binary, FirefoxProfile profile, ICapabilities capabilities, TimeSpan commandTimeout) : base(FirefoxDriver.CreateExtensionConnection(binary, profile, commandTimeout), FirefoxDriver.RemoveUnneededCapabilities(capabilities))
 {
     this.binary  = binary;
     this.profile = profile;
 }
        private static IWebDriver CreateNewWebDriver(string webBrowserName, BrowserType type, out IntPtr mainWindowHandle, string driversDirectory)
        {
            webBrowserName = webBrowserName.ToLower();
            IWebDriver     iWebDriver            = null;
            List <Process> processesBeforeLaunch = GetProcesses();
            string         newProcessFilter      = string.Empty;

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

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

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

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

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

            mainWindowHandle = (newProcess != null) ? newProcess.MainWindowHandle : IntPtr.Zero;
            return(iWebDriver);
        }
Exemple #39
0
        public static bool IsMarionette(IWebDriver driver)
        {
            Firefox.FirefoxDriver firefoxDriver = driver as Firefox.FirefoxDriver;

            return(firefoxDriver != null && firefoxDriver.IsMarionette);
        }
        static void Main(string[] args)
        {   // test with firefox
            IWebDriver driver = new OpenQA.Selenium.Firefox.FirefoxDriver();

            // test with IE
            //InternetExplorerOptions options = new InternetExplorerOptions();
            //options.IntroduceInstabilityByIgnoringProtectedModeSettings = true;
            //IWebDriver driver = new OpenQA.Selenium.IE.InternetExplorerDriver(options);
            SetupTest();
            driver.Navigate().GoToUrl(baseURL + "Account/Login.aspx");
            IWebElement inputTextUser = driver.FindElement(By.Id("MainContent_LoginUser_UserName"));

            inputTextUser.Clear();
            driver.FindElement(By.Id("MainContent_LoginUser_UserName")).Clear();
            driver.FindElement(By.Id("MainContent_LoginUser_UserName")).SendKeys("usuario");
            driver.FindElement(By.Id("MainContent_LoginUser_Password")).Clear();
            driver.FindElement(By.Id("MainContent_LoginUser_Password")).SendKeys("123");
            driver.FindElement(By.Id("MainContent_LoginUser_LoginButton")).Click();
            driver.Navigate().GoToUrl(baseURL + "finanzas/consulta.aspx");
            // view combo element
            IWebElement comboBoxSistema = driver.FindElement(By.Id("MainContent_rcbSistema_Arrow"));

            //Then click when menu option is visible
            comboBoxSistema.Click();
            System.Threading.Thread.Sleep(500);
            // container of elements systems combo
            IWebElement listaDesplegableComboSistemas = driver.FindElement(By.Id("MainContent_rcbSistema_DropDown"));

            listaDesplegableComboSistemas.FindElement(By.XPath("//li[text()='BOMBEO MECANICO']")).Click();
            System.Threading.Thread.Sleep(500);
            IWebElement comboBoxEquipo = driver.FindElement(By.Id("MainContent_rcbEquipo_Arrow"));

            //Then click when menu option is visible
            comboBoxEquipo.Click();
            System.Threading.Thread.Sleep(500);
            // container of elements equipment combo
            IWebElement listaDesplegableComboEquipos = driver.FindElement(By.Id("MainContent_rcbEquipo_DropDown"));

            listaDesplegableComboEquipos.FindElement(By.XPath("//li[text()='MINI-V']")).Click();
            System.Threading.Thread.Sleep(500);
            driver.FindElement(By.Id("MainContent_Button1")).Click();
            try
            { Assert.AreEqual("BOMBEO MECANICO_22", driver.FindElement(By.XPath("//*[@id=\"MainContent_RejillaRegistroFinanciero_ctl00_ctl04_LabelSistema\"]")).Text); }
            catch (AssertionException e)
            { verificationErrors.Append(e.Message); }
            // verify coin format $1,234,567.89 usd
            try
            { Assert.IsTrue(Regex.IsMatch(driver.FindElement(By.XPath("//*[@id=\"MainContent_RejillaRegistroFinanciero_ctl00_ctl04_labelInversionInicial\"]")).Text, "\\$((,)*[0-9]*[0-9]*[0-9]+)+(\\.[0-9]{2})? usd")); }
            catch (AssertionException e)
            { verificationErrors.Append(e.Message); }
            try
            { Assert.IsTrue(Regex.IsMatch(driver.FindElement(By.XPath("//*[@id=\"MainContent_RejillaRegistroFinanciero_ctl00_ctl04_labelCostoOpMantto\"]")).Text, "\\$((,)*[0-9]*[0-9]*[0-9]+)+(\\.[0-9]{2})? usd")); }
            catch (AssertionException e)
            { verificationErrors.Append(e.Message); }
            try
            { Assert.IsTrue(Regex.IsMatch(driver.FindElement(By.XPath("//*[@id=\"MainContent_RejillaRegistroFinanciero_ctl00_ctl04_labelCostoEnergia\"]")).Text, "\\$((,)*[0-9]*[0-9]*[0-9]+)+(\\.[0-9]{2})? usd")); }
            catch (AssertionException e)
            { verificationErrors.Append(e.Message); }
            try
            { Assert.IsTrue(Regex.IsMatch(driver.FindElement(By.XPath("//*[@id=\"MainContent_RejillaRegistroFinanciero_ctl00_ctl04_labelcostoUnitarioEnergia\"]")).Text, "\\$((,)*[0-9]*[0-9]*[0-9]+)+(\\.[0-9]{2})? usd")); }
            catch (AssertionException e)
            { verificationErrors.Append(e.Message); }
            // verify number format 1,234,567.89
            try
            { Assert.IsTrue(Regex.IsMatch(driver.FindElement(By.XPath("//*[@id=\"MainContent_RejillaRegistroFinanciero_ctl00_ctl04_labelConsumo\"]")).Text, "((,)*[0-9]*[0-9]*[0-9]+)+(\\.[0-9]{2})?")); }
            catch (AssertionException e)
            { verificationErrors.Append(e.Message); }
            System.Console.WriteLine("errores: " + verificationErrors);
            System.Threading.Thread.Sleep(20000);
            driver.Quit();
        }
Exemple #41
0
 public FirefoxDriver(FirefoxDriverService service, FirefoxOptions options, TimeSpan commandTimeout) : base(new DriverServiceCommandExecutor(service, commandTimeout), FirefoxDriver.ConvertOptionsToCapabilities(options))
 {
 }
        static void Main(string[] args)
        {
            try
            {
                string baseUrl = "http://www.amazon.com/";
                if (args.Length >= 1)
                {
                    baseUrl = args[0];
                }

                string filename;
                if (args.Length >= 2)
                {
                    filename = args[1];
                }
                else
                {
                    Uri uri = new Uri(baseUrl);
                    filename = uri.Host.Replace(".", "-") + @".har";
                }

                // Uncomment to enable SSL support
                // Fiddler.CONFIG.IgnoreServerCertErrors = true;
                // FiddlerApplication.Prefs.SetBoolPref("fiddler.network.streaming.abortifclientaborts", true);

                // Varibale to store the list of items downloaded
                var sessions         = new List <Fiddler.Session>();
                var newSessions      = new List <Fiddler.Session>();
                int browserProcessId = -1;

                // As each HTTP item is downloaded add it to our list.
                // We will export this list later.
                Fiddler.FiddlerApplication.AfterSessionComplete += delegate(Fiddler.Session oS)
                {
                    Monitor.Enter(sessions);
                    // Only record HTTP traffic by our browser process
                    if (browserProcessId == oS.LocalProcessID)
                    {
                        sessions.Add(oS);
                    }
                    Monitor.Exit(sessions);
                };

                Fiddler.FiddlerApplication.BeforeRequest += delegate(Fiddler.Session oS)
                {
                    // Record the process id for the first URL we go to,
                    // this is the browser that we lanched with Selenium
                    // Could also do extra verification here, for example
                    // check that it is a child process, of this process.
                    // That requires some heavy Win32 API usage, so I've
                    // skipped it here.
                    if (browserProcessId == -1 && oS.fullUrl == baseUrl)
                    {
                        browserProcessId = oS.LocalProcessID;
                    }

                    // Only record HTTP traffic by our browser process
                    if (browserProcessId == oS.LocalProcessID)
                    {
                        Monitor.Enter(newSessions);
                        newSessions.Add(oS);
                        Monitor.Exit(newSessions);
                    }
                };

                // Start Fiddler on port 8877.
                // Register as the system wide proxy.
                Fiddler.FiddlerApplication.Startup(8877, FiddlerCoreStartupFlags.Default);

                /////////////////////////////////////////////////
                // Begin selenium test
                /////////////////////////////////////////////////

                var webDriver = new OpenQA.Selenium.Firefox.FirefoxDriver();
                var selenium  = new Selenium.WebDriverBackedSelenium(webDriver, baseUrl);

                selenium.Start();
                selenium.Open(baseUrl);

                // Wait until 3 seconds of HTTP idle (no request being processed for 3 seconds)
                // or a 30 second timeout.
                // 'result' will be false if items are still being downloaded when the timeout
                // occurs.
                bool result = WaitHttpIdle(sessions, 3000, 30000);
                selenium.Stop();

                /////////////////////////////////////////////////
                // End selenium test
                /////////////////////////////////////////////////

                // Load the HAR file exporter (this only has to be done once per process).
                // The following DLL was downloaded from:
                // https://www.fiddler2.com/dl/FiddlerCore-BasicFormats.zip
                // It is currently only loadable with FiddlerCode 2.2.9.9.
                String path = Path.Combine(Path.GetDirectoryName
                                               (Assembly.GetExecutingAssembly().Location), @"FiddlerCore-BasicFormats.dll");
                FiddlerApplication.oTranscoders.ImportTranscoders(path);

                // Export fiddler sessions to HAR file
                Monitor.Enter(sessions);
                var oExportOptions = new Dictionary <string, object>();
                oExportOptions.Add("Filename", filename);
                bool fiddler = Fiddler.FiddlerApplication.DoExport("HTTPArchive v1.2", sessions.ToArray(), oExportOptions, null);
                sessions.Clear();
                Monitor.Exit(sessions);
            }
            finally
            {
                // Shutdown fiddler, this removes Fiddler as the system proxy.
                Fiddler.FiddlerApplication.Shutdown();
                Thread.Sleep(500);
            }
        }
Exemple #43
0
 public FirefoxDriver(ICapabilities capabilities) : this(FirefoxDriver.ExtractBinary(capabilities), FirefoxDriver.ExtractProfile(capabilities), capabilities, RemoteWebDriver.DefaultCommandTimeout)
 {
 }
Exemple #44
0
        private QA.IWebDriver InitWebDriver()
        {
            QA.IWebDriver theDriver = null;
            switch (this.browser)
            {
            case Browsers.IE:
            {
                InternetExplorerDriverService driverService = InternetExplorerDriverService.CreateDefaultService(Application.StartupPath + "\\drivers\\");
                driverService.HideCommandPromptWindow = true;
                driverService.SuppressInitialDiagnosticInformation = true;
                ds = driverService;
                QA.IE.InternetExplorerOptions _ieOptions = new QA.IE.InternetExplorerOptions();
                _ieOptions.IntroduceInstabilityByIgnoringProtectedModeSettings = true;
                theDriver = new QA.IE.InternetExplorerDriver(driverService, _ieOptions);
                ProcessID = driverService.ProcessId;
            }; break;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            default:
            {
                QA.IE.InternetExplorerOptions _ieOptions = new QA.IE.InternetExplorerOptions();
                _ieOptions.IntroduceInstabilityByIgnoringProtectedModeSettings = true;
                theDriver = new QA.IE.InternetExplorerDriver(_ieOptions);
            }; break;
            }
            return(theDriver);
        }