Beispiel #1
0
        public void TestExplicitWait()
        {
            IWebDriver driver = new ChromeDriver(@"C:\ChromeDriver");
            driver.Navigate().GoToUrl("http://dl.dropbox.com/u/55228056/AjaxDemo.html");

            try
            {
             			    IWebElement page4button = driver.FindElement(By.LinkText("Page 4"));
             			    page4button.Click();

               WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
               IWebElement message = wait.Until<IWebElement>((d) =>
               {
                    return d.FindElement(By.Id("page4"));
               });

             			    Assert.IsTrue(message.Text.Contains("Nunc nibh tortor"));

             		    }
            catch (NoSuchElementException e)
            {
             			    Assert.Fail("Element not found!!");
             		    } finally {
             			    driver.Close();
             		    }
        }
         //碳结圆钢价格行情
         public static void GetData(string linkName, int marketId)
         { 
             IWebDriver driver = new ChromeDriver();
             try
             {
                 driver.Manage().Window.Maximize();
                 driver.Navigate().GoToUrl("http://www.mysteel.com/");
                 var userName = driver.FindElement(By.Name("my_username"));
                 userName.SendKeys("tx6215");
                 var password = driver.FindElement(By.Name("my_password"));
                 password.SendKeys("tx6215");
                 userName.Submit();
                 var steel = driver.FindElement(By.LinkText("结构钢"));
                 driver.Navigate().GoToUrl(steel.GetAttribute("href"));
                 Thread.Sleep(2000);

                 var carbonRound = driver.FindElement(By.LinkText("碳圆"));
                 driver.Navigate().GoToUrl(carbonRound.GetAttribute("href"));
                 Thread.Sleep(2000);
                 var date = DateTime.Now.Day + "日";
                 GetPage(driver, linkName, marketId);
             }
             finally
             {
                 driver.Close();
                 driver.Quit();
             }
         }
Beispiel #3
0
        static void Main(string[] args)
        {
            // create an instance of webdriver
            IWebDriver driver = new ChromeDriver();

            // go to web page
            driver.Navigate().GoToUrl("http://www.thetestroom.com/webapp");

            // click on the about link
            driver.FindElement(By.Id("about_link")).Click();

            // check that the about page has the about zoo title
            String title = driver.Title;

            if (title.Equals("About Zoo"))
            {
                Console.WriteLine("Found the about page with the value of " + title);
            }
            else
            {
                Console.WriteLine("Instead found page with: " + title);
            }

            // close the driver
            driver.Close();
        }
        public void HomepageLoads_CalendarIsReachable()
        {
            // Instantiate a new web driver to run the test

            //Implicit Path (Default)
            IWebDriver driver = new ChromeDriver();

            //Explicit Path
            //IWebDriver driver = new ChromeDriver("\\\\psf\\Home\\Documents\\GitHubVisualStudio\\imentor\\UnitTests\\");

            // Instruct the driver to throw an error if it has to wait more than 5 seconds for retrieval, then go to URL
            driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(5));
            driver.Navigate().GoToUrl("https://imast.azurewebsites.net");

            // To verify that the homepage is online and reachable, we save the url after navigating and check it
            String HomeUrl = driver.Url;
            Assert.AreEqual("https://imast.azurewebsites.net/#!/", HomeUrl);

            // Our home page is the Listings page. Test that it has loaded by comparing the title element to "Listings"
            String PrimaryHeader = driver.FindElement(By.ClassName("im-form-label")).Text;
            Assert.AreEqual("Upcoming Events", PrimaryHeader);

            // Our home page also has a collection of filters. Test that they have loaded by checking their text tags.

            String FilterHeader = driver.FindElement(By.XPath("//*[@id=\"main-content\"]/div/div/div/div/div[4]/div[1]/div/div[2]/div[2]/md-content/md-list/md-list-item[1]/div")).Text;
            String FilterMath = driver.FindElement(By.XPath("//*[@id=\"main-content\"]/div/div/div/div/div[4]/div[1]/div/div[2]/div[2]/md-content/md-list/md-list-item[2]/div/div[1]")).Text;
            String FilterScience = driver.FindElement(By.XPath("//*[@id=\"main-content\"]/div/div/div/div/div[4]/div[1]/div/div[2]/div[2]/md-content/md-list/md-list-item[3]/div/div")).Text;
            String FilterHistory = driver.FindElement(By.XPath("//*[@id=\"main-content\"]/div/div/div/div/div[4]/div[1]/div/div[2]/div[2]/md-content/md-list/md-list-item[4]/div/div")).Text;
            String FilterReading = driver.FindElement(By.XPath("//*[@id=\"main-content\"]/div/div/div/div/div[4]/div[1]/div/div[2]/div[2]/md-content/md-list/md-list-item[5]/div/div")).Text;
            String FilterCompSci = driver.FindElement(By.XPath("//*[@id=\"main-content\"]/div/div/div/div/div[4]/div[1]/div/div[2]/div[2]/md-content/md-list/md-list-item[6]/div/div")).Text;

            // Assert that all the text tags are correct.
            Assert.AreEqual("Subjects", FilterHeader);
            Assert.AreEqual("Math", FilterMath);
            Assert.AreEqual("Science", FilterScience);
            Assert.AreEqual("History", FilterHistory);
            Assert.AreEqual("Reading", FilterReading);
            Assert.AreEqual("Computer Science", FilterCompSci);

            // Next we find the Calendar Button and click it to navigate to the Calendar
            IWebElement CalendarButton = driver.FindElement(By.ClassName("glyphicon-calendar"));
            CalendarButton.Click();

            // To verify that the calendar loaded, we check the "today button"
            String Today = driver.FindElement(By.ClassName("fc-today-button")).Text;
            Assert.AreEqual("today", Today);

            // Also verify the other calendar buttons, month, week, and day.
            String Month = driver.FindElement(By.ClassName("fc-month-button")).Text;
            Assert.AreEqual("month", Month);

            String Week = driver.FindElement(By.ClassName("fc-basicWeek-button")).Text;
            Assert.AreEqual("week", Week);

            String Day = driver.FindElement(By.ClassName("fc-basicDay-button")).Text;
            Assert.AreEqual("day", Day);

            // End the test by closing the browser
            driver.Close();
        }
Beispiel #5
0
        public void TestWithImplicitWait()
        {
            //Go to the Demo AjAX Application
            IWebDriver driver = new ChromeDriver(@"C:\ChromeDriver");
            driver.Navigate().GoToUrl("http://dl.dropbox.com/u/55228056/AjaxDemo.html");

            //Set the Implicit Wait time Out to 10 Seconds
            driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(10));

             		    try {

             			    //Get link for Page 4 and click on it
             			    IWebElement page4button = driver.FindElement(By.LinkText("Page 4"));
             			    page4button.Click();

             			    //Get an element with id page4 and verify it's text
             			    IWebElement message = driver.FindElement(By.Id("page4"));
             			    Assert.IsTrue(message.Text.Contains("Nunc nibh tortor"));
             		    }
            catch (NoSuchElementException e)
            {
             			    Assert.Fail("Element not found!!");
             		    }
            finally
            {
                driver.Close();
             		    }
        }
Beispiel #6
0
        public void TestJavaScript()
        {
            IWebDriver driver = new ChromeDriver(@"C:\ChromeDriver\");
            driver.Navigate().GoToUrl("http://www.google.com");

            Screenshot screenshot = ((ITakesScreenshot)driver).GetScreenshot();
            screenshot.SaveAsFile(@"c:\temp\main_page.png", System.Drawing.Imaging.ImageFormat.Png);

            driver.Close();
        }
Beispiel #7
0
        public void logo()
        {
            IWebDriver browser = new OpenQA.Selenium.Chrome.ChromeDriver();

            browser.Navigate().GoToUrl(GoodsUrl);
            browser.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(30);
            IWebElement cont = browser.FindElement(By.Id("headerLogo"));

            cont.Click();
            browser.Close();
        }
        public void SimpleLoginTest()
        {
            IWebDriver driver;
                //driver = new FirefoxDriver();

                //internet explorer needs the path to it's
                //helper executable ...but don't worry, you won't
                //want to use IE for reasons that'll become very
                //evident...!
                //driver = new InternetExplorerDriver(@"c:\grid2");

                //chrome needs chromedriver.exe ... parameter is the PATH
                //to wherever the .exe is...
                driver = new ChromeDriver(@"c:\grid2");

                #region waitforit..
                //sometimes selenium jumps the gun and declares an element isn't available
                //when, if it'd just wait a second (or 10) the element would be available.
                //here we tell selenium to hold it's horses and wait a cotton pickin' minute
                //if it can't find something, wait up to 10 seconds for it to appear
                //driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(10));
                #endregion //waitforit..

                driver.Url = "http://*****:*****@value='Log On']"));

                Assert.NotNull(usernameEntry);
                Assert.NotNull(passwordEntry);
                Assert.NotNull(logOnButton);

                usernameEntry.SendKeys("test002");
                passwordEntry.SendKeys("test002");
                logOnButton.Click();

                var logoffLink = driver.FindElement(By.LinkText("Log Off"));
                Assert.NotNull(logoffLink,"log off element not found");
            */
                #endregion i can haz login?

                driver.Close();
                driver.Quit();
        }
Beispiel #9
0
        public void TestExplicitWaitByTitle()
        {
            IWebDriver driver = new ChromeDriver(@"C:\ChromeDriver");
            driver.Navigate().GoToUrl("http://www.google.com");
            IWebElement query = driver.FindElement(By.Name("q"));
            query.SendKeys("selenium");
            query.Submit();

            WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
            wait.Until((d) => { return d.Title.ToLower().StartsWith("selenium"); });
            Assert.IsTrue(driver.Title.ToLower().StartsWith("selenium"));
            driver.Close();
        }
Beispiel #10
0
        static void Main(string[] args)
        {
            Random rand = new Random();

            var driver   = new OpenQA.Selenium.Chrome.ChromeDriver();
            int index    = 0;
            int willWait = 0;

            driver.Navigate().GoToUrl("http://www.quality.gskp.by/2");
            while (1 == 1)
            {
                try
                {
                    var element = driver.FindElement(By.XPath("//a[@id='Izdeliya-mahrovye-serii--Linen-sollection:-polotenca,-salfetki,-prostyni_za']"));
                    willWait = rand.Next(3000, 5000);
                    Console.WriteLine("\t Searching for the element [" + willWait + "]...");
                    System.Threading.Thread.Sleep(willWait);

                    willWait = rand.Next(3000, 5000);
                    Console.WriteLine("\tMoving to the button [" + willWait + "]...");
                    Actions scroll = new Actions(driver);
                    scroll.MoveToElement(element);
                    System.Threading.Thread.Sleep(willWait);

                    willWait = rand.Next(3000, 5000);
                    element.Click();
                    Console.WriteLine("\tClicking [" + willWait + "]...");

                    Console.WriteLine("I click " + index++ + " times!");
                    if (index == 1000000)
                    {
                        driver.Close();
                        Console.WriteLine("I cannot do it more!");
                        Console.ReadLine();
                        Environment.Exit(0);
                    }

                    System.Threading.Thread.Sleep(willWait);
                    driver.Navigate().Refresh();
                    Console.WriteLine("\tRefreshing...");
                }
                catch (Exception)
                {
                    willWait = rand.Next(3000, 10000);
                    Console.WriteLine("!!Some exception [" + willWait + "]...");
                    driver.Quit();
                    driver = new ChromeDriver();
                    driver.Navigate().GoToUrl("http://www.quality.gskp.by/2");
                }
            }
        }
        public void ExecuteTest()
        {
            IWebDriver driver = new ChromeDriver();
            driver.Navigate().GoToUrl("http://google.com");

            IWebElement element = driver.FindElement(By.Name("q"));

            element.SendKeys("selenium example using c#");

            Console.WriteLine("Executed Test");

            driver.Close();
            driver.Quit();
        }  
Beispiel #12
0
        public void TestDragDrop()
        {
            IWebDriver driver = new ChromeDriver(@"C:\ChromeDriver\");
            driver.Navigate().GoToUrl("http://dl.dropbox.com/u/55228056/DragDropDemo.html");

            IWebElement source = driver.FindElement(By.Id("draggable"));
            IWebElement target = driver.FindElement(By.Id("droppable"));

            Actions builder = new Actions(driver);
            builder.DragAndDrop(source, target).Perform();
            Assert.AreEqual("Dropped!", target.Text);

            driver.Close();
        }
 public void TestThatGoogleFindsJavaNotCsharp()
 {
     ChromeOptions options = new ChromeOptions();
     options.AddArgument("--no-sandbox");
     options.AddArgument("--disable-extensions");
     options.AddArgument("--start-maximized");
     IWebDriver driver = new ChromeDriver(options);
     driver.Navigate().GoToUrl("http://google.com");
     driver.FindElement(By.Id("lst-ib")).SendKeys("Java");
     driver.FindElement(By.Name("btnK")).Submit();
     Thread.Sleep(1000);
     Assert.IsTrue(driver.FindElement(By.CssSelector("#rso > div > div:nth-child(1) > div > h3 > a")).Text.Contains("Java"));
     Assert.IsFalse(driver.FindElement(By.CssSelector("#rso > div > div:nth-child(1) > div > h3 > a")).Text.Contains("C#"));
     driver.Close();
 }
Beispiel #14
0
        public void TestJavaScript()
        {
            IWebDriver driver = new ChromeDriver(@"C:\ChromeDriver\");
            driver.Navigate().GoToUrl("http://www.google.com");

            IJavaScriptExecutor js = (IJavaScriptExecutor) driver;

            String title = (String)js.ExecuteScript("return document.title");
            Assert.AreEqual("Google", title);

            long links = (long)js.ExecuteScript("var links = document.getElementsByTagName('A'); return links.length");
            Assert.AreEqual(41, links); //Count of links may change

            driver.Close();
        }
Beispiel #15
0
        public void Manipulate()
        {
            ChromeDriver driver = new ChromeDriver();
            HelpFunctions H = new HelpFunctions();

             H.Navigate("http://us14.chatzy.com/37785015405504", driver);
            H.Navigate("http://us14.chatzy.com", driver);
            driver.Manage().Timeouts().ImplicitlyWait(new TimeSpan(0, 0, 100));
            WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(5));
            IWebElement element = null;
               //= wait.Until(ExpectedConditions.ElementIsVisible(By.ClassName("X967")));

            H.Button("//*[@id='X313']", driver);//Login/SignUp
            driver.Manage().Timeouts().ImplicitlyWait(new TimeSpan(0, 0, 30));
            element = wait.Until(ExpectedConditions.ElementIsVisible(By.XPath("//*[@id='X603']")));

            H.InputInfo("//*[@id='X603']", "*****@*****.**", driver);//add email
            driver.Manage().Timeouts().ImplicitlyWait(new TimeSpan(0, 0, 30));

            H.Button("//*[@id='X6001']", driver); // choose the "I am regitered user"
            driver.Manage().Timeouts().ImplicitlyWait(new TimeSpan(0, 0, 30));

            H.InputInfo("//*[@id='X604']", "Amber001", driver); //Enter in the password
            driver.Manage().Timeouts().ImplicitlyWait(new TimeSpan(0, 0, 30));

            H.Button("//*[@id='X593']", driver); //click the ok button

            element = wait.Until(ExpectedConditions.ElementIsVisible(By.ClassName("X967")));
            H.Navigate("http://us14.chatzy.com/37785015405504", driver);

            H.Button("//*[@id='X593']", driver); //click the enter room button
            H.Button("//*[@id='X1049']", driver);

            var chat = driver.FindElementById("X184");
               // System.Collections.ObjectModel.ReadOnlyCollection<IWebElement> chat = driver.FindElementsByClassName("a");
               // chat.ToString();

            List<string> Temp = new List<string>();
            Temp.Add(chat.Text);
            System.IO.File.AppendAllLines(@"OUTPUT3.txt", Temp);
            string[] t = System.IO.File.ReadAllLines(@"OUTPUT3.txt");
            t.ToList();

             //   string s = chat.Text;
            //    string[] words = Regex.Split(s, "\r\n");
            driver.Close();
        }
 public void SuccessfulLogin()
 {
     ChromeOptions options = new ChromeOptions();
     options.AddArgument("--no-sandbox");
     options.AddArgument("--disable-extensions");
     options.AddArgument("--start-maximized");
     IWebDriver driver = new ChromeDriver(options);
     driver.Navigate().GoToUrl("http://www.qa.way2automation.com/");
     driver.FindElement(By.CssSelector("#load_form > h3"));
     driver.FindElement(By.CssSelector("#load_form > div > div.span_3_of_4 > p > a[href='#login']")).Click();
     driver.FindElement(By.CssSelector("#load_form > fieldset:nth-child(5) > input[name='username']")).SendKeys("j2bwebdriver");
     driver.FindElement(By.CssSelector("#load_form > fieldset:nth-child(6) > input[name='password']")).SendKeys("j2bwebdriver");
     driver.FindElements(By.CssSelector("#load_form > div > div.span_1_of_4 > input"))[1].Submit();
     Thread.Sleep(3000);
     Assert.IsFalse(driver.FindElement(By.CssSelector("body")).Text.Contains("Username"));
     Assert.IsFalse(driver.FindElement(By.CssSelector("body")).Text.Contains("Password"));
     driver.Close();
 }
Beispiel #17
0
        public void TestDoubleClick()
        {
            IWebDriver driver = new ChromeDriver(@"C:\ChromeDriver\");
            driver.Navigate().GoToUrl("http://dl.dropbox.com/u/55228056/DoubleClickDemo.html");

            IWebElement message = driver.FindElement(By.Id("message"));

            //Verify color is Blue
            Assert.AreEqual("rgba(0, 0, 255, 1)",message.GetCssValue("background-color").ToString());

            Actions builder = new Actions(driver);
            builder.DoubleClick(message).Build().Perform();

            //Verify Color is Yellow
            Assert.AreEqual("rgba(255, 255, 0, 1)",message.GetCssValue("background-color").ToString());

            driver.Close();
        }
Beispiel #18
0
         public static void SetData(int marketId,string linkText,bool isGoOn, int priceIndex)
         { 
            IWebDriver driver = new ChromeDriver();
            try
            {
                driver.Manage().Window.Maximize();
                driver.Navigate().GoToUrl("http://www.f139.com/");

                var loginName = driver.FindElement(By.Id("userName"));
                loginName.SendKeys("zh15295667405");
                var loginPassword = driver.FindElement(By.Id("passWord"));
                loginPassword.SendKeys("15295667405");
                var loginBtn = driver.FindElement(By.ClassName("btn_login"));
                loginBtn.Click();

                var ferroalloyUrls = driver.FindElements(By.LinkText("废钢网"));
                driver.Navigate().GoToUrl(ferroalloyUrls[0].GetAttribute("href"));
                Thread.Sleep(2000);

                var silicon = driver.FindElement(By.LinkText("数据"));
                driver.Navigate().GoToUrl(silicon.GetAttribute("href"));
                Thread.Sleep(2000);

                var gc = driver.FindElement(By.LinkText("钢材"));
                driver.Navigate().GoToUrl(gc.GetAttribute("href"));
                Thread.Sleep(2000);

                var linkName = driver.FindElement(By.LinkText(linkText));
                driver.Navigate().GoToUrl(linkName.GetAttribute("href"));
                Thread.Sleep(2000);

                GetData(driver, marketId, isGoOn, priceIndex);

                foreach (Price price in PriceList)
                {
                    PriceHelper.SavePrice(price);
                }
            }
            finally
            {
                driver.Close();
                driver.Quit();
            }
         }
Beispiel #19
0
        static void Main(string[] args)
        {
            var driver = new ChromeDriver(); // Should work in other Browser Drivers

            string baseLink = "http://www.codeproject.com";

            //foreach (var link in links)
            for (int i = 2326; i > 2325; i--)
            {
                string link = baseLink + i.ToString();
                driver.Navigate().GoToUrl(link);
                try
                {
                    var login = driver.FindElementById("Button1");
                    var uName = driver.FindElementByName("lname");
                    var pass = driver.FindElementByName("passw");
                    uName.SendKeys("admin");
                    pass.SendKeys("*******");
                    login.Submit();
                }
                catch
                {
                    //already logged in

                }
                Screenshot ss = ((ITakesScreenshot)driver).GetScreenshot();

                //Use it as you want now
                string screenshot = ss.AsBase64EncodedString;
                byte[] screenshotAsByteArray = ss.AsByteArray;
                FileNameFromURL fileNameFromURL = new ConsoleApplication1.FileNameFromURL();
                string filePath = Application.StartupPath + fileNameFromURL.ConvertToWindowsFileName(link) + ".jpg";
                if (File.Exists(filePath))
                {
                    File.Delete(filePath);
                }
                ss.SaveAsFile(filePath, ImageFormat.Png); //use any of the built in image formating
                ss.ToString();//same as string screenshot = ss.AsBase64EncodedString;

            }
            //driver.Dispose();
            driver.Close();
        }
Beispiel #20
0
        public static void Browse(string username, Action<SouthwindBrowser> action)
        {
            var selenium = new ChromeDriver();

            var browser = new SouthwindBrowser(selenium);
            try
            {
                browser.Login(username, username);
                action(browser);
            }
            catch (UnhandledAlertException)
            {
                selenium.SwitchTo().Alert();

            }
            finally
            {
                selenium.Close();
            }
        }
Beispiel #21
0
        public void GoogleSearchTest()
        {
            //IWebDriver driver = new FirefoxDriver();
            IWebDriver driver = new ChromeDriver();
            driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(10));

            //ChromeDriver driver = new ChromeDriver();
            string homepageURL = "http://google.com";

            // driver.Navigate().GoToUrl(baseURL);
            string searchText = "Manual testing is long";

            GooglePage pageObject = new GooglePage(driver);
            pageObject.openPage(homepageURL);
            pageObject.SearchCriteria = searchText;
            pageObject.DoTheSearch();

            Assert.IsTrue(pageObject.ResultCount > 0, "zero results found");

            driver.Close();
        }
        public void Execute()
        {
            String outputPath = localDesktop + String.Format(@"\WebTest\{0}_{1:yyyy-MM-dd_hh-mm-ss-tt}", "firefox", DateTime.Now);
            
            IWebDriver driver_firefox = new FirefoxDriver();
            AllPagesFound(driver_firefox, "firefox", outputPath);
            RunInputSuite(driver_firefox, "firefox", outputPath);
            driver_firefox.Close();
            
            outputPath = localDesktop + String.Format(@"\WebTest\{0}_{1:yyyy-MM-dd_hh-mm-ss-tt}", "chrome", DateTime.Now);
            IWebDriver driver_chrome = new ChromeDriver(chromeDriverPath);
            RunInputSuite(driver_chrome, "chrome", outputPath);
            driver_chrome.Close();

            //disabling IE, machine may need registry edits to get it to work
            /*
            outputPath = localDesktop + String.Format(@"\WebTest\{0}_{1:yyyy-MM-dd_hh-mm-ss-tt}", "explorer", DateTime.Now);
            IWebDriver driver_explorer = new InternetExplorerDriver(IEDriverPath);
            RunInputSuite(driver_explorer, "chrome", outputPath);
            driver_explorer.Close();*/
        }
Beispiel #23
0
         //冶金焦、铸造焦
         public void Run()
         { 
            IWebDriver driver = new ChromeDriver();
            try
            {
                driver.Manage().Window.Maximize();
                driver.Navigate().GoToUrl("http://data.f139.com/list.do?pid=3&vid=126");

                var loginNames = driver.FindElements(By.Id("userName"));
                if(loginNames.Count > 0)
                {
                    var loginName = loginNames[0];
                    loginName.SendKeys("zh15295667405");
                    var loginPassword = driver.FindElement(By.Id("passWord"));
                    loginPassword.SendKeys("15295667405");
                    var loginBtn = driver.FindElement(By.Id("submitbtn"));
                    loginBtn.Click();
                }
                var divP = driver.FindElement(By.Id("thjprolist"));
                var divs = divP.FindElements(By.TagName("div"));
                var yCokeDiv = divs[8].FindElement(By.LinkText("冶金焦"));//冶金焦链接
                //var zCokeDiv = divs[8].FindElement(By.LinkText("铸造焦"));//铸造焦链接
                driver.Navigate().GoToUrl(yCokeDiv.GetAttribute("href"));
                GetData(driver);
                var divPz = driver.FindElement(By.Id("thjprolist"));
                var divSz = divPz.FindElements(By.TagName("div"));
                var zCokeDiv = divSz[8].FindElement(By.LinkText("铸造焦"));//铸造焦链接
                driver.Navigate().GoToUrl(zCokeDiv.GetAttribute("href"));
                GetData(driver);

                foreach(Price price in PriceList)
                {
                    PriceHelper.SavePrice(price);
                }
            }
            finally {
                driver.Close();
                driver.Quit();
            }
         }
 public void TestThatGoogleFindsCheeseNotBacon()
 {
     // Setup ChromeDriver configuration
     ChromeOptions options = new ChromeOptions();
     options.AddArgument("--no-sandbox");
     options.AddArgument("--disable-extensions");
     options.AddArgument("--start-maximized");
     IWebDriver driver = new ChromeDriver(options);
     // Choose page link
     driver.Navigate().GoToUrl("http://google.com");
     // Setup ChromeDriver configuration
     driver.FindElement(By.Id("lst-ib")).SendKeys("Cheese");
     driver.FindElement(By.Name("btnK")).Submit();
     // Wait for webelements to load
     Thread.Sleep(1000);
     // Assertion on first search result position		
     Assert.IsTrue(driver.FindElement(By.CssSelector("#rso > div > div:nth-child(1) > div > h3 > a")).Text.Contains("Cheese"));
     Assert.IsTrue(driver.FindElement(By.CssSelector("#rso > div > div:nth-child(1) > div > h3 > a")).Text.Contains("Wikipedia"));
     Assert.IsFalse(driver.FindElement(By.CssSelector("#rso > div > div:nth-child(1) > div > h3 > a")).Text.Contains("Bacon"));
     // Closing browser window
     driver.Close();
 }
Beispiel #25
0
        static void Main(string[] args)
        {
            IWebDriver driver = new ChromeDriver();

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

            IWebElement element = driver.FindElement(By.Name("q"));
            element.SendKeys("CAA");
            element.Submit();

            try
            {
            IWebElement results = driver.FindElement(By.CssSelector("h3.r"));

            Console.WriteLine("Page title is " + results.Text);
            Console.ReadKey();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.ReadKey();
                driver.Close();
            }
        }
Beispiel #26
0
        // Функция чтобы получить куки для обычного HttpRequest или моего SimpleBrowser - проблема в том что на сайте посольства очень интересная проверка на подленость юзера
        public void GetCookiesFromDrive()
        {
            using (var Driver = new ChromeDriver())
            {
                Globals.IdService = 1;
                Globals.IdCity = 92;
                Driver.Manage().Window.Maximize();
                Driver.Navigate().GoToUrl("https://secure.e-konsulat.gov.pl/Uslugi/RejestracjaTerminu.aspx?IDUSLUGI=" + Globals.IdService + "&IDPlacowki=" + Globals.IdCity);

                if (Globals.IsElementDisplayed(Driver, By.Id("cp_KomponentObrazkowy_CaptchaImageID")))
                {
                    var cookies = Driver.Manage().Cookies.AllCookies;

                    StreamWriter streamWriter = new StreamWriter(@"Cookies\" + Globals.cookieFileNameGuid + ".txt");

                    foreach (var result in cookies)
                    {
                        var cookieExpires = result.Expiry;
                        var cookieDomain = result.Domain;
                        var cookiePath = result.Path;
                        var cookieName = result.Name;
                        var cookieValue = result.Value;

                        var cookieString = cookieName + ";" + cookieValue + ";" + cookiePath + ";" + cookieDomain + ";" + cookieExpires;

                        streamWriter.WriteLine(cookieString);
                        Console.WriteLine(cookieString);

                        Cookie cookieNew = new Cookie(cookieName, cookieValue, cookiePath, cookieDomain);
                        if (cookieExpires != null) cookieNew.Expires = (DateTime)cookieExpires;
                        CapthaBrowser.Cookies.Add(cookieNew);
                    }
                    streamWriter.Close();
                    Driver.Close();
                    MessageBox.Show("Cookies has been saved!");
                }
                else
                {
                    MessageBox.Show("Error!");
                    Driver.Close();
                }
            }
        }
Beispiel #27
0
 private static void Google()
 {
     var driver = new ChromeDriver();
     driver.Url = "http://google.co.uk";
     driver.Close();
 }
Beispiel #28
0
        //硅铬
        public void Run()
        {
            IWebDriver driver = new ChromeDriver();
            try
            {
                driver.Manage().Window.Maximize();
                driver.Navigate().GoToUrl("http://www.f139.com/");

                var loginName = driver.FindElement(By.Id("userName"));
                loginName.SendKeys("f13853998584");
                var loginPassword = driver.FindElement(By.Id("passWord"));
                loginPassword.SendKeys("138539");
                var loginBtn = driver.FindElement(By.ClassName("btn_login"));
                loginBtn.Click();

                var ferroalloyUrls = driver.FindElements(By.LinkText("铁合金网"));
                driver.Navigate().GoToUrl(ferroalloyUrls[0].GetAttribute("href"));
                Thread.Sleep(2000);

                var silicon = driver.FindElement(By.LinkText("铬系"));
                driver.Navigate().GoToUrl(silicon.GetAttribute("href"));
                Thread.Sleep(2000);

                var demosticPrice = driver.FindElement(By.LinkText("国内价格"));
                driver.Navigate().GoToUrl(demosticPrice.GetAttribute("href"));
                Thread.Sleep(2000);

                var date = DateTime.Now.GetDateTimeFormats('M')[0].ToString();
                var ferrosilicons = driver.FindElements(By.LinkText(date + "国内主要地区硅铬市场价格汇总"));
                if (ferrosilicons.Count > 0)
                {
                    driver.Navigate().GoToUrl(ferrosilicons[0].GetAttribute("href"));
                    Thread.Sleep(2000);

                    var dateSpan = driver.FindElement(By.ClassName("cGray")).Text;
                    var infoparts = dateSpan.Split(new[] { "   " }, StringSplitOptions.RemoveEmptyEntries);
                    var pubTimeStr = infoparts[0];
                    DateTime pdate;
                    if (!DateTime.TryParse(pubTimeStr, out pdate))
                    {
                        pdate = DateTime.Now;
                    }
                    var zwDiv = driver.FindElement(By.Id("zhengwen"));
                    var table = zwDiv.FindElement(By.TagName("table"));
                    var trs = table.FindElement(By.TagName("tbody")).FindElements(By.TagName("tr"));
                    var firstTds = trs[0].FindElements(By.TagName("th"));
                    var titleTxt = firstTds[3].Text.Trim();//获取含有单位title的文本
                    var unit = titleTxt.Substring(titleTxt.IndexOf("(") + 1, titleTxt.IndexOf(")") - (titleTxt.IndexOf("(") + 1));//单位
                    List<Price> pList = new List<Price>();

                    for (int i = 1; i < trs.Count; i++)
                    {
                        var p = new Price
                        {
                            Date = pdate,
                            PriceUnit = unit,
                            MarketCrmId = MarketId
                        };

                        var tds = trs[i].FindElements(By.TagName("td"));//找到一行数据的所有列
                        var tags = new string[3];//把价格列之前的所有数据用|隔开组成一个字符串
                        for (int j = 0; j < 3; j++)
                        {
                            tags[j] = tds[j].Text;
                        }
                        string token = "|" + String.Join("|", tags) + "|";
                        p.Token = token;

                        var priceStr = tds[3].Text.Trim();//找到价格列的值
                        if (string.IsNullOrEmpty(priceStr) || priceStr == "-")
                        {
                            p.HPirce = null;
                            p.LPrice = null;
                        }
                        else
                        {
                            if (priceStr.Contains("-"))
                            {
                                int ind = priceStr.IndexOf("-");
                                if (ind > 0)
                                {
                                    var priceL = priceStr.Substring(0, ind);//最低价
                                    var priceH = priceStr.Substring(ind + 1);//最高价
                                    p.LPrice = decimal.Parse(priceL);
                                    p.HPirce = decimal.Parse(priceH);
                                }
                            }
                            else
                            {
                                decimal price;
                                if (!decimal.TryParse(priceStr, out price))
                                {
                                    p.HPirce = null;
                                    p.LPrice = null;
                                }
                                else
                                {
                                    p.LPrice = price;
                                    //p.HPirce = price;
                                }
                            }
                        }

                        var tdDelta = tds[4].Text.Trim();//涨跌
                        if (!string.IsNullOrEmpty(tdDelta))
                        {
                            var firstTxt = tdDelta.Substring(0, 1);
                            if (firstTxt == "涨")
                            {
                                p.Delta = decimal.Parse(tdDelta.Substring(1));
                            }
                            else if (firstTxt == "跌")
                            {
                                p.Delta = -decimal.Parse(tdDelta.Substring(1));
                            }
                            else if (firstTxt == "平")
                            {
                                p.Delta = null;
                            }
                        }
                        else
                        {
                            p.Delta = null;
                        }

                        if (p.HPirce.HasValue && p.LPrice.HasValue)
                        {
                            p.Spread = (p.HPirce.Value + p.LPrice.Value) / 2;
                        }

                        pList.Add(p);
                        if (p.Token == "|四川|Si+Cr≥72%,C≤0.1%|硅铬|")
                        {
                            var jsPrice = new Price
                            {
                                Token = "|江苏|Si+Cr≥72%,C≤0.1%|硅铬|",
                                PriceUnit = p.PriceUnit,
                                MarketCrmId = p.MarketCrmId,
                                Date = p.Date,
                                HPirce = p.HPirce,
                                LPrice = p.LPrice,
                                Delta = p.Delta,
                                Spread = p.Spread
                            };
                            var zjPrice = new Price {
                                Token = "|浙江|Si+Cr≥72%,C≤0.1%|硅铬|",
                                PriceUnit = p.PriceUnit,
                                MarketCrmId = p.MarketCrmId,
                                Date = p.Date,
                                HPirce = p.HPirce,
                                LPrice = p.LPrice,
                                Delta = p.Delta,
                                Spread = p.Spread
                            };
                            pList.Add(jsPrice);
                            pList.Add(zjPrice);
                        }
                    }

                    foreach (Price price in pList)
                    {
                        PriceHelper.SavePrice(price);
                    }
                }
            }
            finally
            {
                driver.Close();
                driver.Quit();
            }
        }
Beispiel #29
0
         public static void GetData(string divID, string linkName, string cityName)
         {
             IWebDriver driver = new ChromeDriver();
             try
             {
                 driver.Manage().Window.Maximize();
                 driver.Navigate().GoToUrl("http://www.mysteel.com/");
                 var userName = driver.FindElement(By.Name("my_username"));
                 userName.SendKeys("tx6215");
                 var password = driver.FindElement(By.Name("my_password"));
                 password.SendKeys("tx6215");
                 userName.Submit();

                 var hsteel = driver.FindElement(By.LinkText("硅钢"));
                 driver.Navigate().GoToUrl(hsteel.GetAttribute("href"));
                 Thread.Sleep(2000);

                 var mDiv = driver.FindElements(By.ClassName("mRow"))[0].FindElement(By.ClassName("rRihgt")).FindElement(By.ClassName("box")).FindElement(By.Id(divID));
                 var moreLi = mDiv.FindElement(By.ClassName("more"));
                 var link = moreLi.FindElement(By.TagName("a"));
                 driver.Navigate().GoToUrl(link.GetAttribute("href"));
                 Thread.Sleep(2000);

                 var date = DateTime.Now.Day + "日";
                 var sh = driver.FindElement(By.LinkText(date + linkName));
                 if (sh != null)
                 {
                     driver.Navigate().GoToUrl(sh.GetAttribute("href"));
                     Thread.Sleep(2000);

                     var timeSpan = driver.FindElement(By.ClassName("info")).Text;
                     var timeSplit = timeSpan.Split(new[] { " " }, StringSplitOptions.RemoveEmptyEntries);
                     var pubTime = timeSplit[0];
                     DateTime pdate;
                     if (!DateTime.TryParse(pubTime, out pdate))
                     {
                         pdate = DateTime.Now;
                     }

                     var table = driver.FindElement(By.Id("text22222")).FindElement(By.TagName("table"));
                     var trs = table.FindElement(By.TagName("tbody")).FindElements(By.TagName("tr"));
                     var firstTds = trs[0].FindElements(By.TagName("td"));
                     var titleTxt = firstTds[4].Text.Trim();
                     var unit = titleTxt.Substring(titleTxt.IndexOf("(") + 1, titleTxt.IndexOf(")") - (titleTxt.IndexOf("(") + 1));//单位

                     for (int i = 2; i < trs.Count; i++)
                     {
                         var p = new Price
                         {
                             Date = pdate,
                             PriceUnit = unit,
                             MarketCrmId = MarketId
                         };
                         var tds = trs[i].FindElements(By.TagName("td"));//找到一行数据的所有列
                         var tags = new string[4];//把价格列之前的所有数据用|隔开组成一个字符串
                         for (int j = 0; j < 4; j++)
                         {
                             tags[j] = tds[j].Text;
                         }
                         string token = "|" + cityName + "|" + String.Join("|", tags) + "|";
                         p.Token = token;

                         var priceStr = tds[4].Text.Trim();//找到价格列的值
                         if (string.IsNullOrEmpty(priceStr) || priceStr == "-")
                         {
                             p.HPirce = null;
                             p.LPrice = null;
                         }
                         else
                         {
                             if (priceStr.Contains("-"))
                             {
                                 int ind = priceStr.IndexOf("-");
                                 if (ind > 0)
                                 {
                                     var priceL = priceStr.Substring(0, ind);//最低价
                                     var priceH = priceStr.Substring(ind + 1);//最高价
                                     p.LPrice = decimal.Parse(priceL);
                                     p.HPirce = decimal.Parse(priceH);
                                 }
                             }
                             else
                             {
                                 decimal price;
                                 if (!decimal.TryParse(priceStr, out price))
                                 {
                                     p.HPirce = null;
                                     p.LPrice = null;
                                 }
                                 else
                                 {
                                     p.LPrice = price;
                                     //p.HPirce = price;
                                 }
                             }
                         }

                         var tdDelta = tds[5].Text.Trim();//涨跌
                         if (!string.IsNullOrEmpty(tdDelta) && tdDelta != "-")
                         {
                             var firstTxt = tdDelta.Substring(0, 1);
                             if (firstTxt == "+")
                             {
                                 p.Delta = decimal.Parse(tdDelta.Substring(1));
                             }
                             else if (firstTxt == "-")
                             {
                                 p.Delta = -decimal.Parse(tdDelta.Substring(1));
                             }
                         }
                         else
                         {
                             p.Delta = null;
                         }

                         if (p.HPirce.HasValue && p.LPrice.HasValue)
                         {
                             p.Spread = (p.HPirce.Value + p.LPrice.Value) / 2;
                         }

                         var desc = tds[6].Text;//备注
                         p.Comment = desc;
                         PriceHelper.SavePrice(p);
                     }
                 }

             }
             finally
             {
                 driver.Close();
                 driver.Quit();
             }
         }
Beispiel #30
0
        public static UserInfo Activate(Methods method, string igg_id, string promo)
        {
            ChromeDriverService service = ChromeDriverService.CreateDefaultService();

            service.HideCommandPromptWindow = true;

            var options = new ChromeOptions();

            options.AddArgument("--window-position=-32000,-32000,performance");
            options.AddArgument("--headless");

            IWebDriver driver = new OpenQA.Selenium.Chrome.ChromeDriver(service, options);

            if (method == Methods.IGG_ID)
            {
                try
                {
                    driver.Manage().Window.Minimize();
                    driver.Navigate().GoToUrl("https://lordsmobile.igg.com/gifts/");

                    By igg_idInputElement = By.XPath("//input[@class='myname']");
                    By codeInputElement   = By.XPath("//input[@class='mycode']");
                    By claimButton        = By.Id("btn_claim_1");
                    By doneMessageElement = By.Id("msg");

                    var igg    = driver.FindElement(igg_idInputElement);
                    var code   = driver.FindElement(codeInputElement);
                    var submit = driver.FindElement(claimButton);

                    igg.Click();
                    igg.SendKeys(igg_id);
                    code.Click();
                    code.SendKeys(promo);
                    submit.Click();

                    var donemsg = driver.FindElement(doneMessageElement);
                    if (donemsg.Text != "Время действия кода истекло.[base]" && donemsg.Text != "Этот код уже был активирован!" && donemsg.Text != "Вы ввели неверный код.[C02]")
                    {
                        driver.Close();
                        driver.Quit();
                        return(new UserInfo()
                        {
                            Kingdom = 0, Power = "0", Result = Results.Sucess
                        });
                    }
                    else if (donemsg.Text == "Вы ввели неверный код.[C02]")
                    {
                        driver.Close();
                        driver.Quit();
                        return(new UserInfo()
                        {
                            Kingdom = 0, Power = "0", Result = Results.Invalid_Code
                        });
                    }
                    else if (donemsg.Text == "Время действия кода истекло.[base]")
                    {
                        driver.Close();
                        driver.Quit();
                        return(new UserInfo()
                        {
                            Kingdom = 0, Power = "0", Result = Results.Expired_Code
                        });
                    }
                    else if (donemsg.Text == "Этот код уже был активирован!")
                    {
                        driver.Close();
                        driver.Quit();
                        return(new UserInfo()
                        {
                            Kingdom = 0, Power = "0", Result = Results.Already_Activated
                        });
                    }
                    else
                    {
                        driver.Close();
                        driver.Quit();
                        return(new UserInfo()
                        {
                            Kingdom = 0, Power = "0", Result = Results.System_Error
                        });
                    }
                }
                catch
                {
                    return(new UserInfo()
                    {
                        Kingdom = 0, Power = "0", Result = Results.System_Error
                    });
                }
            }
            else if (method == Methods.Nickname)
            {
                try
                {
                    driver.Manage().Window.Minimize();
                    driver.Navigate().GoToUrl("https://lordsmobile.igg.com/gifts/");

                    var methodfind = driver.FindElement(By.ClassName("tab-list-2"));
                    methodfind.Click();
                    var nicknameInputfind = driver.FindElement(By.XPath("//input[@id='charname']"));
                    nicknameInputfind.Click();
                    nicknameInputfind.SendKeys(igg_id);
                    var code = driver.FindElement(By.XPath("//input[@id='cdkey_2']"));
                    code.Click();
                    code.SendKeys(promo);
                    var submit = driver.FindElement(By.Id("btn_claim_2"));
                    submit.Click();
                    var donemsg = driver.FindElement(By.Id("msg"));
                    if (donemsg.Text != "Игрок с таким именем не существует")
                    {
                        var    extramsg = driver.FindElement(By.Id("extra_msg"));
                        int    king     = int.Parse(Regex.Match(extramsg.Text, "Королевство: #(.*)").Groups[1].Value);
                        string pow      = (Regex.Match(extramsg.Text, "Сила: (.*)").Groups[1].Value);
                        var    submit2  = driver.FindElement(By.Id("btn_confirm"));
                        submit2.Click();

                        var donemsg2 = driver.FindElement(By.Id("msg"));
                        if (donemsg2.Text != "Время действия кода истекло.[base]" && donemsg2.Text != "Этот код уже был активирован!" && donemsg2.Text != "Вы ввели неверный код.[C02]")
                        {
                            driver.Close();
                            driver.Quit();
                            return(new UserInfo()
                            {
                                Kingdom = king, Power = pow, Result = Results.Sucess
                            });
                        }
                        else if (donemsg2.Text == "Вы ввели неверный код.[C02]")
                        {
                            driver.Close();
                            driver.Quit();
                            return(new UserInfo()
                            {
                                Kingdom = 0, Power = "0", Result = Results.Invalid_Code
                            });
                        }
                        else if (donemsg2.Text == "Время действия кода истекло.[base]")
                        {
                            driver.Close();
                            driver.Quit();
                            return(new UserInfo()
                            {
                                Kingdom = 0, Power = "0", Result = Results.Expired_Code
                            });
                        }
                        else if (donemsg2.Text == "Этот код уже был активирован!")
                        {
                            driver.Close();
                            driver.Quit();
                            return(new UserInfo()
                            {
                                Kingdom = king, Power = pow, Result = Results.Already_Activated
                            });
                        }
                        else
                        {
                            driver.Close();
                            driver.Quit();
                            return(new UserInfo()
                            {
                                Kingdom = 0, Power = "0", Result = Results.System_Error
                            });
                        }
                    }
                    else
                    {
                        driver.Close();
                        driver.Quit();
                        return(new UserInfo()
                        {
                            Kingdom = 0, Power = "0", Result = Results.Invalid_Nickname
                        });
                    }
                }
                catch
                {
                    driver.Close();
                    driver.Quit();
                    return(new UserInfo()
                    {
                        Kingdom = 0, Power = "0", Result = Results.System_Error
                    });
                }
            }
            else
            {
                driver.Close();
                driver.Quit();
                return(new UserInfo()
                {
                    Kingdom = 0, Power = "0", Result = Results.System_Error
                });
            }
        }
Beispiel #31
0
		public void Run()
		{
			IWebDriver driver = new ChromeDriver();
			try
			{
				
				driver.Manage().Window.Maximize();

				driver.Navigate().GoToUrl("http://list1.mysteel.com/market/p-405-----010211-0--------1.html");
				var loginNames = driver.FindElements(By.Name("my_username"));
				if (loginNames.Count > 0)
				{
					loginNames[0].SendKeys("tx6215");
					//not logined
					var loginPwds = driver.FindElements(By.Name("my_password"));
					loginPwds[0].SendKeys("tx6215");

					loginNames[0].Submit();
				}

				var d = DateTime.Today.Day;
				var ts = driver.FindElements(By.LinkText(d.ToString(CultureInfo.InvariantCulture) + "日上海市场拉丝材价格行情"));
				driver.Navigate().GoToUrl(ts[0].GetAttribute("href"));
				Thread.Sleep(2000);


				//get publish time
				var infos = driver.FindElement(By.ClassName("info")).Text;
				var infoparts = infos.Split(new[] {" "}, StringSplitOptions.RemoveEmptyEntries);
				var pubTimeStr = infoparts[0];

				DateTime pdt;
				if (!DateTime.TryParse(pubTimeStr, out pdt))
				{
					pdt = DateTime.Now;
				}

				var priceLines =
					driver.FindElement(By.Id("marketTable")).FindElement(By.TagName("tbody")).FindElements(By.TagName("tr"));

				for (int i = 1; i < priceLines.Count; i++)
				{
					var p = new Price
						        {
							        Date = pdt,
							        MarketCrmId = MarketId
						        };

					var fields = priceLines[i].FindElements(By.TagName("td"));
					var tags = new string[5];
					for (int j = 0; j < 5; j++)
					{
						tags[j] = fields[j].Text;
					}
					string token = "|" + String.Join("|", tags) + "|";
					p.Token = token;

					var priceStr = fields[5].Text.Trim();
					decimal priceD;
					if (string.IsNullOrWhiteSpace(priceStr) || priceStr == "-" || !decimal.TryParse(priceStr, out priceD))
					{
						p.LPrice = null;
					}
					else
					{
						p.LPrice = priceD;
					}

					var deltaStr = fields[6].Text.Trim();
					decimal deltaD;
					if (string.IsNullOrWhiteSpace(deltaStr) || priceStr == "-" || !decimal.TryParse(deltaStr, out deltaD))
					{
						p.Delta = null;
					}
					else
					{
						p.Delta = deltaD;
					}

					p.Comment = fields[7].Text.Trim();
					PriceHelper.SavePrice(p);
				}
			}
			finally
			{
				driver.Close();
				driver.Quit();
			}
			
		}
Beispiel #32
0
        static void Run(string[] args)
        {
            var chromeDriverPath = string.Concat(AppDomain.CurrentDomain.BaseDirectory, "driver");
            bool enableCustomJustification = false;

            string urlLogin = ConfigurationManager.AppSettings[CONFIG_PONTO_LOGIN_URL];
            if (string.IsNullOrEmpty(urlLogin))
                throw new InvalidOperationException(string.Format("Url de login do sistema de ponto não definida! Verifique a chave \"{0}\" no app.config.", CONFIG_PONTO_LOGIN_URL));

            string username = ConfigurationManager.AppSettings[CONFIG_USERNAME];
            if (string.IsNullOrEmpty(username))
                throw new InvalidOperationException(string.Format("Nome de usuário não configurado! Verifique a chave \"{0}\" no app.config.", CONFIG_USERNAME));

            string password = ConfigurationManager.AppSettings[CONFIG_PASSWORD];
            if (string.IsNullOrEmpty(password))
                throw new InvalidOperationException(string.Format("Senha de usuário não configurada! Verifique a chave \"{0}\" no app.config.", CONFIG_PASSWORD));

            if (!bool.TryParse(ConfigurationManager.AppSettings[CONFIG_ENABLE_JUSTIFICATION], out enableCustomJustification))
                enableCustomJustification = false;

            string inputApontamento = string.Empty;

            if (args == null || !args.Any())
            {
                Console.WriteLine("Informe o apontamento:  1-Entrada. 2-Início almoço. 3-Volta Almoço. 4-Saída.");
                inputApontamento = Console.ReadLine();
            }
            else
            {
                inputApontamento = args[0];
            }

            Console.WriteLine("");

            int apontamento = 0;
            if (!int.TryParse(inputApontamento, out apontamento))
                throw new InvalidOperationException(string.Format("Apontamento não definido corretamente. Valor informado: \"{0}\"! Utilize:  1-Entrada.  2-Início almoço.  3-Volta Almoço.  4-Saída.", inputApontamento));

            using (var driver = new ChromeDriver(chromeDriverPath))
            {
                driver.Navigate().GoToUrl(urlLogin);

                var usernameField = driver.FindElementById("ctl00_m_g_1f2f91c5_726b_47c3_a64d_34117653e0e4_ctl00_signInControl_UserName");
                var passwordField = driver.FindElementById("ctl00_m_g_1f2f91c5_726b_47c3_a64d_34117653e0e4_ctl00_signInControl_Password");
                var buttonLogin = driver.FindElementById("ctl00_m_g_1f2f91c5_726b_47c3_a64d_34117653e0e4_ctl00_signInControl_LoginButton");

                usernameField.Clear();
                usernameField.SendKeys(username);

                passwordField.Clear();
                passwordField.SendKeys(password);

                buttonLogin.Click();

                IWait<IWebDriver> firstWait = new WebDriverWait(driver, TimeSpan.FromSeconds(90));
                firstWait.Until(x => driver.FindElementById("entrada") != null);

                string btnApontamentoId = string.Empty;

                switch ((Apontamento)apontamento)
                {
                    case Apontamento.ENTRADA:
                        btnApontamentoId = "entrada";
                        break;

                    case Apontamento.INICIO_ALMOCO:
                        btnApontamentoId = "inicioAlmoco";
                        break;

                    case Apontamento.VOLTA_ALMOCO:
                        btnApontamentoId = "voltaAlmoco";
                        break;

                    case Apontamento.SAIDA:
                        btnApontamentoId = "saida";
                        break;
                }

                var btnApontamento = driver.FindElementById(btnApontamentoId);
                btnApontamento.Click();

                IWait<IWebDriver> secondWait = new WebDriverWait(driver, TimeSpan.FromSeconds(90));
                secondWait.Until(x => driver.FindElementById("entrada") != null);

                if ((Apontamento)apontamento == Apontamento.SAIDA)
                {
                    try
                    {
                        driver.SwitchTo().DefaultContent();

                        var dialogIFrame = driver.FindElement(By.Id(""));
                        driver.SwitchTo().Frame(dialogIFrame);

                        var textAreaJustificativa = driver.FindElement(By.Id("ctl00_m_g_cac22e8d_9ad5_4163_b85d_7254c3524eac_ctl00_txtJustificativa"));
                        var btnConfirmarJustificativa = driver.FindElement(By.Id("ctl00_m_g_cac22e8d_9ad5_4163_b85d_7254c3524eac_ctl00_btnSalvar"));

                        string justificativa = ".";

                        if (enableCustomJustification)
                        {
                            Console.WriteLine("::");
                            Console.WriteLine(":: Informe a justificativa das horas extras: ");
                            justificativa = Console.ReadLine();

                            Console.WriteLine();
                        }

                        textAreaJustificativa.SendKeys(justificativa);
                        btnConfirmarJustificativa.Click();

                        IWait<IWebDriver> thirdWait = new WebDriverWait(driver, TimeSpan.FromSeconds(90));
                        thirdWait.Until(x => driver.FindElementById("entrada") != null);
                    }
                    catch(Exception ex)
                    {
                        Console.WriteLine(string.Concat("Erro: ", ex.Message));
                        Console.WriteLine("::");
                        Console.WriteLine("::");
                        Console.WriteLine(ex.ToString());
                        Console.WriteLine("");
                    }
                    finally
                    {
                        driver.SwitchTo().DefaultContent();
                    }
                }

                driver.Close();
            }
        }
Beispiel #33
-1
        public void TestPlayAnEntireGame()
        {
            IWebDriver driver = null;
            try
            {
                driver = new ChromeDriver(@"C:\Repositories\ExamProject\Test\SeleniumFiles");
                driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(10));
                driver.Navigate().GoToUrl("localhost:13777");

                driver.FindElement(By.Id("nameInput")).SendKeys("Jens");
                driver.FindElement(By.Id("btnHard")).Click();
                driver.FindElement(By.Id("startButton")).Click();

                Assert.IsTrue(driver.Url.EndsWith("ingame.aspx"));
                int guess = 1;
                string outputMessage = string.Empty;
                while (outputMessage != "Success!")
                {
                    driver.FindElement(By.Id("guessInput")).SendKeys("" + guess);
                    driver.FindElement(By.Id("guessButton")).Click();
                    Thread.Sleep(70);//make sure JS is done, could probaly be lower
                    outputMessage = driver.FindElement(By.ClassName("advice")).Text;
                    guess++;
                }
                Thread.Sleep(500);//There is a delay before going to the next page
                Assert.AreEqual("YOU WON!", driver.FindElement(By.ClassName("headline")).Text);
                Thread.Sleep(5000);//Use this time to marvel at the High Score
            }
            finally
            {
                driver.Close();
                driver.Quit();
            }
        }