Exemple #1
0
        public PlatformApiCollection Codecademy([FromBody] EmailRequestModel emailRequest)
        {
            string value = emailRequest.Email;

            bool exists = false, timedOut = false, driverOld = false;

            var webDriverWaitUntilTimeout = new TimeSpan(0, 0, 5);

            DateTime TestedAt             = DateTime.Now;

            if (value == null)
            {
                throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.UnsupportedMediaType, String.Format("Request Body Error! Empty key/value pair or wrong content type, please use x-www-form-urlencoded.")));
            }

            var driver = new PhantomJSDriver(GetPhantomJSDriverService(driverOld));

            driver.Navigate().GoToUrl("https://www.codecademy.com/");

            WebDriverWait wait = new WebDriverWait(driver, webDriverWaitUntilTimeout);

            try
            {
                var username = wait.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementIsVisible(By.Name("user[username]")));
                username.SendKeys(RandomString(15));

                var user_email = wait.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementIsVisible(By.Name("user[email]")));
                user_email.SendKeys(value);

                var user_password = wait.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementIsVisible(By.Name("user[password]")));
                user_password.SendKeys(RandomString(15));

                var error = wait.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementIsVisible(By.CssSelector("ul[class^='fieldErrors']")));

                if (error.Text.Contains("Email is already taken"))
                {
                    driver.Quit();
                    exists = true;
                }
            }
            catch (Exception ex)
            {
                if (ex is WebDriverException)
                {
                    timedOut = true;
                }

                driver.Quit();
                exists = false;
            }

            PlatformApiCollection PAC = new PlatformApiCollection
            {
                Platforms = GetPlatformModel("Codecademy", value, exists, TestedAt, GetPoints(exists, 4), timedOut)
            };

            CalculateTotalPoints(exists, value, "Codecademy", GetPoints(exists, 4));

            return(PAC);
        }
Exemple #2
0
        public PlatformApiCollection StackOverflowChecker([FromBody] EmailRequestModel emailRequest)
        {
            string value = emailRequest.Email;

            bool exists = false, timedOut = false, driverOld = true;

            var webDriverWaitUntilTimeout = new TimeSpan(0, 0, 15);

            DateTime TestedAt             = DateTime.Now;

            if (value == null)
            {
                throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.UnsupportedMediaType, String.Format("Request Body Error! Empty key/value pair or wrong content type, please use x-www-form-urlencoded.")));
            }

            var driver = new PhantomJSDriver(GetPhantomJSDriverService(driverOld));

            driver.Navigate().GoToUrl("https://stackoverflow.com/users/signup");

            WebDriverWait wait = new WebDriverWait(driver, webDriverWaitUntilTimeout);

            try
            {
                var user_email = wait.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementIsVisible(By.CssSelector("#email")));
                user_email.SendKeys(value);

                var user_password = wait.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementIsVisible(By.CssSelector("#password")));
                user_password.SendKeys("FakePassw0rD1@");

                var submit_button = wait.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementIsVisible(By.CssSelector("#submit-button")));
                submit_button.Click();

                var error = wait.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementIsVisible(By.CssSelector("#mainbar-full > div:nth-child(2) > div > div")));

                if ((error.Text.Contains("The email address you have used is already registered.")))
                {
                    driver.Quit();
                    exists = true;
                }
            }
            catch (Exception ex)
            {
                if (ex is WebDriverException)
                {
                    timedOut = false;

                    driver.Quit();
                    exists = false;
                }
            }

            PlatformApiCollection PAC = new PlatformApiCollection
            {
                Platforms = GetPlatformModel("StackOverflow", value, exists, TestedAt, GetPoints(exists, 2), timedOut)
            };

            CalculateTotalPoints(exists, value, "Stack Overflow", GetPoints(exists, 2));

            return(PAC);
        }
Exemple #3
0
 private void Init()
 {
     if (webDriver != null)
     {
         webDriver.Quit();
     }
     webDriver = new PhantomJSDriver();
 }
Exemple #4
0
 public void Reinitialize(string login, string password)
 {
     lock (_networkSync)
     {
         _phantom.Quit();
         InitPhantom(login, password);
     }
 }
Exemple #5
0
        public PlatformApiCollection MicrosoftChecker([FromBody] EmailRequestModel emailRequest)
        {
            string value = emailRequest.Email;

            bool exists = false, timedOut = false, driverOld = true;

            var webDriverWaitUntilTimeout = new TimeSpan(0, 0, 10);

            DateTime TestedAt             = DateTime.Now;

            if (value == null)
            {
                throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.UnsupportedMediaType, String.Format("Request Body Error! Empty key/value pair or wrong content type, please use x-www-form-urlencoded.")));
            }

            var driver = new PhantomJSDriver(GetPhantomJSDriverService(driverOld));

            driver.Navigate().GoToUrl("https://signup.live.com/signup?wa=wsignin1.0&wtrealm=urn%3afederation%3aMicrosoftOnline&wctx=estsredirect%3d2%26estsrequest%3drQIIAbPSyigpKSi20tdPTE7OL80r0SvPzEvJLy9OrCotStVLzs_Vyy9Kz0wBsaLYgYJJmTk5SYyGRUJcAi8NHT40Gba57pHO3dXv_8dsFiNHTmYZWNMqRj1C5uoHlyYVJxdlFpRk5ucVX2BkfMHI2MXEYmhgbLyJiSXYMcDzBFPzSblbTIL-RemeKeHFbqkpqUWJINWPmHhDi1OL_PNyKkPys1PzJjHz5eSnZ-bFFxelxafl5JcDBYA2FCQml8SXZCZnp5bsYlYxMUpJNLdMMdI1SzQ21DUxNbLUTTQzN9Q1NE82MzQwMzI3T7Y8wLKB8wKLwC0W1tTE4kyjHyyMi1iBHk1Q_1ki7PPJo6VN--j0NV_fnWLVz9COCMwrNc_N1i71jnAKMi2pzMit9M_Rdklxc_JM9Un3Dw_RLijy9_Uo8bQ1tTLcxUlieAAA0&id=&cbcxt=azubill&lw=1&fl=easi2&bk=1468239878&uaid=f04031e931824586bc1b6dba8f4ffc36&cru=https%3a%2f%2flogin.live.com%2flogin.srf%3fwa%3dwsignin1.0%26wtrealm%3durn%253afederation%253aMicrosoftOnline%26wctx%3destsredirect%253d2%2526estsrequest%253drQIIAbPSyigpKSi20tdPTE7OL80r0SvPzEvJLy9OrCotStVLzs_Vyy9Kz0wBsaLYgYJJmTk5SYyGRUJcAi8NHT40Gba57pHO3dXv_8dsFiNHTmYZWNMqRj1C5uoHlyYVJxdlFpRk5ucVX2BkfMHI2MXEYmhgbLyJiSXYMcDzBFPzSblbTIL-RemeKeHFbqkpqUWJINWPmHhDi1OL_PNyKkPys1PzJjHz5eSnZ-bFFxelxafl5JcDBYA2FCQml8SXZCZnp5bsYlYxMUpJNLdMMdI1SzQ21DUxNbLUTTQzN9Q1NE82MzQwMzI3T7Y8wLKB8wKLwC0W1tTE4kyjHyyMi1iBHk1Q_1ki7PPJo6VN--j0NV_fnWLVz9COCMwrNc_N1i71jnAKMi2pzMit9M_Rdklxc_JM9Un3Dw_RLijy9_Uo8bQ1tTLcxUlieAAA0%26id%3d%26cbcxt%3dazubill%26lw%3d1%26fl%3deasi2%26uaid%3df04031e931824586bc1b6dba8f4ffc36%26lc%3d1033&mkt=EN-US&lc=1033&sl=1&lic=1");

            WebDriverWait wait = new WebDriverWait(driver, webDriverWaitUntilTimeout);

            try
            {
                var user_email = wait.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementIsVisible(By.Id("MemberName")));
                user_email.SendKeys(value);

                var submit_button = wait.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementIsVisible(By.CssSelector("#iSignupAction")));
                submit_button.Click();

                var error = wait.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementIsVisible(By.CssSelector("#MemberNameError")));

                if ((error.Text.Contains("is already a Microsoft account.")) || (error.Text.Contains("Try another name or")))
                {
                    driver.Quit();
                    exists = true;
                }
            }
            catch (Exception ex)
            {
                if (ex is WebDriverException)
                {
                    timedOut = true;
                }

                driver.Quit();
                exists = false;
            }

            PlatformApiCollection PAC = new PlatformApiCollection
            {
                Platforms = GetPlatformModel("Microsoft", value, exists, TestedAt, GetPoints(exists, 6), timedOut)
            };

            CalculateTotalPoints(exists, value, "Microsoft", GetPoints(exists, 6));

            return(PAC);
        }
Exemple #6
0
        public PlatformApiCollection XDAChecker([FromBody] EmailRequestModel emailRequest)
        {
            string value = emailRequest.Email;

            bool exists = false, timedOut = false, driverOld = true;

            var webDriverWaitUntilTimeout = new TimeSpan(0, 0, 10);

            DateTime TestedAt             = DateTime.Now;

            if (value == null)
            {
                throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.UnsupportedMediaType, String.Format("Request Body Error! Empty key/value pair or wrong content type, please use x-www-form-urlencoded.")));
            }

            var driver = new PhantomJSDriver(GetPhantomJSDriverService(driverOld));

            driver.Navigate().GoToUrl("https://forum.xda-developers.com/register.php");

            WebDriverWait wait = new WebDriverWait(driver, webDriverWaitUntilTimeout);

            try
            {
                var username = wait.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementIsVisible(By.CssSelector("#regusername")));
                username.SendKeys(value);

                var user_password = wait.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementIsVisible(By.CssSelector("#regpassword")));
                user_password.Click();

                var error = wait.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementIsVisible(By.CssSelector("#reg_verif_div")));

                if (error.Text.Contains("That username is already in use"))
                {
                    driver.Quit();
                    exists = true;
                }
            }
            catch (Exception ex)
            {
                if (ex is WebDriverException)
                {
                    timedOut = true;
                }

                driver.Quit();
                exists = false;
            }

            PlatformApiCollection PAC = new PlatformApiCollection
            {
                Platforms = GetPlatformModel("XDA Developer", value, exists, TestedAt, GetPoints(exists, 3), timedOut)
            };

            CalculateTotalPoints(exists, value, "XDA Developer", GetPoints(exists, 3));

            return(PAC);
        }
Exemple #7
0
        void pullData(string inputURL, string sportName)
        {
            Console.WriteLine("Starting Pull of " + inputURL);
            PhantomJSDriverService service = PhantomJSDriverService.CreateDefaultService("..\\..\\packages\\PhantomJS.2.1.1\\tools\\phantomjs");

            service.IgnoreSslErrors = true;
            service.SslProtocol     = "any";
            PhantomJSDriver driver = new PhantomJSDriver(service);

            driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(20));

            string source = "";

            try
            {
                driver.Navigate().GoToUrl(inputURL);
                driver.FindElementByClassName("timezone");

                source = driver.PageSource;
            }
            catch (Exception e)
            {
                Helper.writeError(e.ToString(), (fileName + sportName));
            }

            Helper.writePulledData(source, (fileName + sportName));
            driver.Quit();

            Console.WriteLine("Data pulled");
        }
Exemple #8
0
        public void HighBloodPressureImageValidation()
        {
            using (IWebDriver driver = new PhantomJSDriver())
            {
                driver.Navigate().GoToUrl(webAppUri);

                System.Diagnostics.Debug.WriteLine(driver.PageSource);


                IWebElement diastolicElement = driver.FindElement(By.Id("BP_Diastolic"));

                clearTextBox(diastolicElement);
                diastolicElement.SendKeys("90");
                diastolicElement.SendKeys(Keys.Tab);

                IWebElement bodyText = driver.FindElement(By.TagName("body"));
                System.Diagnostics.Debug.WriteLine(bodyText.Text);

                WebDriverWait wait      = new WebDriverWait(driver, TimeSpan.FromSeconds(3));
                IWebElement   ambulance = driver.FindElement(By.Id("ambulanceImage"));

                Assert.IsNotNull(ambulance);

                driver.Quit();
            }
        }
Exemple #9
0
        public void LowBloodPressureTextValidation()
        {
            using (IWebDriver driver = new PhantomJSDriver())
            {
                driver.Navigate().GoToUrl(webAppUri);


                IWebElement systolicElement = driver.FindElement(By.Id("BP_Systolic"));

                clearTextBox(systolicElement);
                systolicElement.SendKeys("70");
                systolicElement.SendKeys(Keys.Tab);

                IWebElement diastolicElement = driver.FindElement(By.Id("BP_Diastolic"));

                clearTextBox(diastolicElement);
                diastolicElement.SendKeys("52");
                diastolicElement.SendKeys(Keys.Tab);

                IWebElement bodyText = driver.FindElement(By.TagName("body"));
                System.Diagnostics.Debug.WriteLine(bodyText.Text);
                StringAssert.Contains(bodyText.Text, "Low Blood Pressure");

                driver.Quit();
            }
        }
Exemple #10
0
        int look()
        {
            var driverService = PhantomJSDriverService.CreateDefaultService(Environment.CurrentDirectory);

            driverService.HideCommandPromptWindow = true;
            IWebDriver driver = new PhantomJSDriver(driverService);

            driver.Navigate().GoToUrl("https://www.truecaller.com/");
            try
            {
                if (driver.PageSource.Contains("Sign out"))
                {
                    return(1);
                }
                else if (driver.PageSource.Contains("Sign in"))
                {
                    return(0);
                }
            }
            catch (Exception e)
            {
                MessageBox.Show("Can't find_out");
                MessageBox.Show(e.Message);
            }
            finally
            {
                driver.Close();
                driver.Quit();
            }
            return(3);
        }
Exemple #11
0
        public List <Song> GetSearch()
        {
            List <Song> search_results = new List <Song>();
            IReadOnlyCollection <IWebElement> search_content;
            List <string> search_content_ids = new List <string>();

            var service = PhantomJSDriverService.CreateDefaultService();

            service.HideCommandPromptWindow = true;
            IWebDriver driver = new PhantomJSDriver(service);

            driver.Url = "http://www.playzer.fr";

            IJavaScriptExecutor js = (IJavaScriptExecutor)driver;


            js.ExecuteScript("arguments[0].click();", driver.FindElement(By.XPath("//*[@id='panel_search']/img")));
            driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(5));
            Thread.Sleep(TimeSpan.FromSeconds(1));
            IWebElement search = driver.FindElement(By.Id("search_engine"));

            search.SendKeys(searchBox.Text);
            driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(5));
            Thread.Sleep(TimeSpan.FromSeconds(2));
            js.ExecuteScript("arguments[0].click();", driver.FindElement(By.XPath("//*[@id='search_clips_tab']")));
            driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(5));
            // Thread.Sleep(TimeSpan.FromSeconds(2));
            driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(5));
            IWebElement result = driver.FindElement(By.Id("search_results"));

            driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(5));
            //  Thread.Sleep(TimeSpan.FromSeconds(2));
            driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(5));
            search_content = result.FindElements(By.XPath("//div[@class='content transition search_item_content']"));
            //   Thread.Sleep(TimeSpan.FromSeconds(2));
            driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(5));

            int i = 1;

            foreach (IWebElement ids in search_content)
            {
                string song_ID = ids.GetAttribute("id");

                string title = driver.FindElement(By.XPath("//*[@id='" + song_ID + "']/div[2]")).Text;

                string artist = driver.FindElement(By.XPath("//*[@id='" + song_ID + "']/div[3]")).Text;

                string url = driver.FindElement(By.XPath("//*[@id='" + song_ID + "']/div[1]/img[2]")).GetAttribute("src");

                search_results.Add(new Song(title, artist, song_ID,
                                            url, i));
                i++;
            }

            driver.Close();
            driver.Quit();
            driver.Dispose();

            return(search_results);
        }
Exemple #12
0
        public static Dictionary <string, double> ExecuteAndRead(string html, IEnumerable <string> elementNames)
        {
            var path = Path.Combine(Default.RangerFolder, fileName);

            // ToDo: Find a way to do this without writing to a file.
            File.WriteAllText(path, html);

            var service = PhantomJSDriverService.CreateDefaultService(Default.RangerFolder);

            service.HideCommandPromptWindow = true;

            var driver   = new PhantomJSDriver(service);
            var filePath = Path.Combine("file:///", path);
            var url      = new Uri(path);

            driver.Navigate().GoToUrl(url);

            var values = new Dictionary <string, double>();

            foreach (var elementName in elementNames)
            {
                var element = driver.FindElement(By.Id(elementName));
                var value   = double.Parse(element.Text);
                values.Add(elementName, value);
            }

            driver.Quit();
            File.Delete(path);

            return(values);
        }
        static void TestPhantom()
        {
            var driverService = PhantomJSDriverService.CreateDefaultService();

            driverService.HideCommandPromptWindow = true;

            var driver = new PhantomJSDriver(driverService);

            driver.Url = "https://www.kak-noviy.ru/sell/phones/apple/iphone-5/64gb-white";
            driver.Manage().Window.Size = new System.Drawing.Size(1920, 1080);
            driver.Navigate();

            var source = driver.PageSource;
            var label1 = driver.FindElementByXPath("//label[text()='Как новый']");
            var label2 = driver.FindElementByXPath("//label[text()='Устройство полностью исправно']");
            var label3 = driver.FindElementByXPath("//label[text()='Полная комплектация']");
            var label4 = driver.FindElementByXPath("//label[text()='Блокировки отсутствуют']");

            label1.Click();
            label2.Click();
            label3.Click();
            label4.Click();
            WaitForAjax(driver);
            driver.GetScreenshot().SaveAsFile("test.png", System.Drawing.Imaging.ImageFormat.Png);
            var price = driver.FindElementByClassName("price");

            Console.WriteLine(price.Text);
            driver.Close();
            driver.Quit();
        }
Exemple #14
0
        private void createMapTileScreenshots(string nodeId, string latitude, string longitude)
        {
            String pathScreenshots = System.IO.Path.GetDirectoryName(System.AppDomain.CurrentDomain.BaseDirectory) + Path.DirectorySeparatorChar + "screenshots" + Path.DirectorySeparatorChar;

            Console.WriteLine("Screenshots Path: " + pathScreenshots);
            try
            {
                // setting for proxy
                //PhantomJSOptions phOptions = new PhantomJSOptions();
                //phOptions.AddAdditionalCapability(CapabilityType.Proxy, "cache.itb.ac.id");

                // hide cmd windows of phantomsjs
                var driverService = PhantomJSDriverService.CreateDefaultService();
                driverService.HideCommandPromptWindow = true;

                // initiate phantomjs driver
                PhantomJSDriver phantom;
                phantom = new PhantomJSDriver(driverService);
                // setting the default timeout to 30 seconds
                phantom.Manage().Timeouts().ImplicitlyWait(new TimeSpan(0, 0, 30));
                string screenshotUrl = "http://localhost/bsts_routing/tilegen/v2/index.php?latitude=" + latitude + "&longitude=" + longitude;
                phantom.Navigate().GoToUrl(screenshotUrl);

                // grab the snapshot
                Screenshot sh        = phantom.GetScreenshot();
                TimeUtils  timeUtils = new TimeUtils();
                string     fileName  = nodeId + "_" + Convert.ToString(timeUtils.ToUnixTime(DateTime.Now)) + ".png";
                sh.SaveAsFile(pathScreenshots + fileName, ImageFormat.Png);
                phantom.Quit();
            }
            catch (Exception error)
            {
                Console.WriteLine(error.Message);
            }
        }
Exemple #15
0
        public List <CityInfo> GetFavoriteCities()
        {
            using (var driver = new PhantomJSDriver())
            {
                var baseUri = new Uri("https://www.gismeteo.ru/");
                driver.Navigate().GoToUrl(baseUri);

                var cities_list = driver.GetInnerElement("div", "class", "main")
                                  .GetInnerElement("div", "class", "column-wrap")
                                  .GetInnerElement("section", "class", "cities cities_frame __frame clearfix")
                                  .GetInnerElement("div", "class", "js_cities_pcities cities_section")
                                  .GetInnerElement("div", "class", "cities_list")
                                  .GetInnerElements("div", "class", "cities_item");

                List <CityInfo> result = new List <CityInfo>();
                if (cities_list != null)
                {
                    foreach (var city_div in cities_list.Where(cd => cd != null))
                    {
                        var city_url = city_div.GetInnerElementAtributeValue("a", "href");
                        if (!string.IsNullOrWhiteSpace(city_url))
                        {
                            var city_name = city_div.GetInnerElementText("span", "class", "cities_name");
                            result.Add(new CityInfo()
                            {
                                Name = city_name, Url = city_url, OuterId = ExtractFromUrl(city_url)
                            });
                        }
                    }
                }
                driver.Quit();
                return(result);
            }
        }
Exemple #16
0
        public static Tuple <string, string> GetPageSource(string url, int waitSecond = 0)
        {
            var options = new PhantomJSOptions();

            options.AddAdditionalCapability("phantomjs.page.settings.userAgent", "Mozilla/5.0 (Windows NT 6.2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.134 Safari/537.36");
            options.AddAdditionalCapability("phantomjs.page.settings.loadImages", false);
            var JsDriver = new PhantomJSDriver(options);

            JsDriver.ExecutePhantomJS("this.onResourceRequested = function(request, net) {" +
                                      "   if (request.url.indexOf('google-analytics') !== -1 || request.url.indexOf('.css') !==-1) {" +
                                      "       net.abort();" +
                                      "   }" +
                                      "};");
            JsDriver.Navigate().GoToUrl(url);

            JsDriver.WaitUntil(d => !d.Url.Contains("duomai.com") &&
                               !d.Url.Contains("guangdiu.com") &&
                               !d.Url.Contains("haohuola.com") &&
                               !d.Url.Contains("zhuayangmao.com") &&
                               !d.Url.Contains("union.") &&
                               !d.Url.Contains("click.taobao"));

            var result  = JsDriver.PageSource;
            var lastUrl = JsDriver.Url;

            JsDriver.Close();
            JsDriver.Quit();

            return(new Tuple <string, string>(result, lastUrl));
        }
Exemple #17
0
        public bool ConnectionTest(string login, string password)
        {
            var service = PhantomJSDriverService.CreateDefaultService();

            service.IgnoreSslErrors = true;
            service.LoadImages      = false;
            service.ProxyType       = "none";
            service.SslProtocol     = "any";

            var options = new PhantomJSOptions();

            options.AddAdditionalCapability("phantomjs.page.settings.userAgent", _phantomJsUserAgent);

            var phantomCheckConnection = new PhantomJSDriver(service, options);

            phantomCheckConnection.Navigate().GoToUrl($"{BaseUrl}/accounts/login");

            phantomCheckConnection.FindElement(By.Id("input_login_email")).SendKeys(login);
            phantomCheckConnection.FindElement(By.Id("input_login_password")).SendKeys(password);
            phantomCheckConnection.FindElement(By.Id("signin_submit")).Click();

            Func <IWebDriver, bool> del = ExpectedConditions.UrlContains($"{BaseUrl}/app/");
            var result = del.Invoke(phantomCheckConnection);

            phantomCheckConnection.Quit();
            return(result);
        }
Exemple #18
0
        /// <summary>
        /// Starting point for the application.
        /// </summary>
        /// <param name="args"> The arguments passed in from the console. </param>
        public static void Main(string[] args)
        {
            PhantomJSDriverService service = PhantomJSDriverService.CreateDefaultService();

            service.IgnoreSslErrors = true;
            service.LoadImages      = false;

            Console.WriteLine("gebruikersnaam");
            string gebruikersnaam = Console.ReadLine();

            Console.WriteLine("wachtwoord");
            string wachtwoord = Console.ReadLine();

            IWebDriver driver = new PhantomJSDriver(service);

            driver.Navigate().GoToUrl("https://mijn.ing.nl/internetbankieren/SesamLoginServlet");

            IWebElement gebruikersnaamElem = driver.FindElement(By.XPath("//div[@id='gebruikersnaam']/descendant::input"));

            gebruikersnaamElem.SendKeys(gebruikersnaam);
            IWebElement wachtwoordElem = driver.FindElement(By.XPath("//div[@id='wachtwoord']/descendant::input"));

            wachtwoordElem.SendKeys(wachtwoord);
            IWebElement button = driver.FindElement(By.CssSelector("button.submit"));

            button.Click();

            ((ITakesScreenshot)driver).GetScreenshot().SaveAsFile("ing.png", ImageFormat.Png);
            System.IO.File.WriteAllText("ing.html", driver.PageSource);

            driver.Quit();

            Console.WriteLine("We are done");
            Console.ReadKey();
        }
        private void PerformSeleniumTests(VisualTesterBase visualTester, Action <IWebDriver> performTests)
        {
            var driver = new PhantomJSDriver();

            driver.Manage().Window.Size = new Size(1280, 980);

            try
            {
                visualTester.Initialize(driver);

                performTests(driver);

                visualTester.Close();
            }
            catch (Exception ex)
            {
                visualTester.Exception(driver);
                Console.WriteLine(ex);
            }
            finally
            {
                driver.Quit();
                visualTester.FinalizeTest();
            }
        }
Exemple #20
0
        void sign_out()
        {
            var driverService = PhantomJSDriverService.CreateDefaultService(Environment.CurrentDirectory);

            driverService.HideCommandPromptWindow = true;
            IWebDriver driver = new PhantomJSDriver(driverService);

            driver.Navigate().GoToUrl("https://www.truecaller.com/");
            try
            {
                var    div = driver.FindElement(By.TagName("div")).FindElement(By.XPath("//*[contains(text(), 'Sign out')]"));
                string js  = "arguments[0].click();";

                ((IJavaScriptExecutor)driver).ExecuteScript(js, div);

                Thread.Sleep(10);


                MessageBox.Show("Signed Out Successfully");
                lbl_Check.Text       = "Signed Out";
                btn_Sign_IN.Enabled  = true;
                btn_Sign_OUT.Enabled = false;
            }
            catch (Exception e)
            {
                MessageBox.Show("You Need to Signed in, In order to get Signed Out");
                MessageBox.Show(e.Message);
            }
            finally
            {
                driver.Close();
                driver.Quit();
            }
        }
Exemple #21
0
        public string xpath_crwal(string url, string xpath0)
        {
            /// <summary>
            /// 利用phantomjs.exe来完成爬虫
            /// 需要在工具--NuGet 程序包管理器--安装几个包
            /// Selenium.PhantomJS.WebDriver和Selenium.WebDriver
            /// </summary>
            /// <param name="url">数据的网址</param>
            /// <param name="xpath0">数据的xpath</param>
            /// <returns></returns>
            PhantomJSDriverService service = PhantomJSDriverService.CreateDefaultService();
            var options = new PhantomJSOptions();

            options.AddAdditionalCapability("phantomjs.page.settings.userAgent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:25.0) Gecko/20100101 Firefox/25.0");
            service.HideCommandPromptWindow = true; // 隐藏dos窗口
            var driver1 = new PhantomJSDriver(service, options);

            driver1.Navigate().GoToUrl(url);


            ReadOnlyCollection <IWebElement> res = driver1.FindElementsByXPath(xpath0); // 搜索嘛,结果肯定是一个数组
            string res_text;

            if (res.Count != 0)
            {
                res_text = res[0].Text;
                driver1.Quit();
            }
            else
            {
                res_text = "NULL";
            }
            return(res_text);
        }
Exemple #22
0
        private IEnumerable <HtmlDocument> GetHtmlDocuments(IEnumerable <string> Urls)
        {
            try
            {
                _log.Info($"Getting html documents...");
                var response = new List <HtmlDocument>();
                _log.Info($"Open webdriver element..");

                using (var driver = new PhantomJSDriver())
                {
                    foreach (var item in Urls)
                    {
                        var sw = Stopwatch.StartNew();
                        _log.Info($"Getting informations for url : {item}");
                        driver.Navigate().GoToUrl(item);
                        _log.Info($"Waiting for parametrized ThreadSleep: {ThreadSleepTime}");
                        Thread.Sleep(ThreadSleepTime);
                        var html = new HtmlDocument();
                        html.LoadHtml(driver.PageSource);
                        response.Add(html);
                        sw.Stop();
                        _log.Info($"ElapsedTime: {sw.ElapsedMilliseconds} ms");
                    }
                    _log.Info($"Closing webdriver element");
                    driver.Quit();
                }
                return(response);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Exemple #23
0
        void pullData(string inputURL, string sportName)
        {
            Console.WriteLine("Starting Pull of " + inputURL);
            PhantomJSDriverService service = PhantomJSDriverService.CreateDefaultService("..\\..\\packages\\PhantomJS.2.1.1\\tools\\phantomjs");

            service.IgnoreSslErrors        = true;
            service.SslProtocol            = "any";
            service.LocalToRemoteUrlAccess = true;
            //service.AddArgument("--ignore-ssl-errors=true");
            // service.AddArgument("--ssl-protocol=tlsv1");
            //service.GhostDriverPath = "E:\\SportsBetting\\packages\\PhantomJS.2.1.1\\tools\\phantomjs";
            //PhantomJSDriver driver = new PhantomJSDriver("E:\\SportsBetting\\packages\\PhantomJS.2.1.1\\tools\\phantomjs");
            PhantomJSDriver driver = new PhantomJSDriver(service);

            driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(20));
            //driver.Url = inputURL;

            string source = "";

            try
            {
                driver.Navigate().GoToUrl(inputURL);
                source = driver.PageSource;
            }
            catch (Exception e)
            {
                Helper.writeError(e.ToString(), (fileName + sportName));
            }

            Helper.writePulledData(source, (fileName + sportName));
            driver.Quit();

            Console.WriteLine("Data pulled");
        }
Exemple #24
0
        private void read_elements(string url)
        {
            //var driver = new ChromeDriver();
            //TimeSpan timer = TimeSpan.FromSeconds(10);
            //driver.Manage().Timeouts().PageLoad = timer;
            //driver.Navigate().GoToUrl(url);
            PhantomJSDriver phantom = new PhantomJSDriver();

            phantom.Navigate().GoToUrl(url);
            //System.Threading.Thread.Sleep(2000);
            HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
            //doc.LoadHtml(driver.PageSource);
            doc.LoadHtml(phantom.PageSource);
            while (doc.DocumentNode.SelectNodes("//*[@id=\"container\"]/channel/div/div/div") == null)
            {
                doc.LoadHtml(phantom.PageSource);
            }
            phantom.Quit();
            string dank  = doc.DocumentNode.SelectNodes("//*[@id=\"container\"]/channel/div/div/div")[0].OuterHtml;
            string danki = Regex.Replace(dank, ".*background-image", "", RegexOptions.Singleline);
            //string danker = danki.Substring(0, 200);
            string dankii = Regex.Replace(danki, "background-color.*", "", RegexOptions.Singleline);
            string danker = Regex.Replace(dankii, "quot", "");
            string why    = Regex.Replace(danker, "[();&]", "");
            string whyy   = Regex.Replace(why, ": url", "");
            string whyyy  = Regex.Replace(whyy, "\\?type=nf720_342.*", "", RegexOptions.Singleline);
            string whyyyy = Regex.Replace(whyyy, " ", "");

            textBox6.AppendText(whyyy + "\n");
            pictureBox1.Load(whyyy + "?type=nf720_342");
        }
        /// <summary>
        /// REFERENCES:
        /// other approach:
        ///
        ///     http://stackoverflow.com/questions/18921099/add-proxy-to-phantomjsdriver-selenium-c
        ///         PhantomJSOptions phoptions = new PhantomJSOptions();
        ///         phoptions.AddAdditionalCapability(CapabilityType.Proxy, "http://localhost:9999");
        ///
        ///     driver = new PhantomJSDriver(phoptions);
        ///     - (24/04/2019) https://stackoverflow.com/a/52446115/3796898
        ///
        /// </summary>
        /// <param name="hostPgUrlPattern"></param>
        /// <param name="freeProxy"></param>
        /// <returns></returns>
        public static string LoadIPProxyDocumentContent(string hostPgUrlPattern, IPProxy freeProxy = null)
        {
            //var options = new ChromeOptions();
            //var userAgent = "user_agent_string";
            //options.AddArgument("--user-agent=" + userAgent);
            //IWebDriver driver = new ChromeDriver(options);

            var service = PhantomJSDriverService.CreateDefaultService(".\\");

            service.HideCommandPromptWindow = true;

            if (freeProxy != null)
            {
                service.ProxyType = freeProxy.Protocol == ProxyProtocolsEnum.HTTP ? "http" : "https:";
                var proxy = new Proxy
                {
                    HttpProxy = $"{freeProxy.IPAddress}:{freeProxy.PortNo}",
                };
                service.Proxy = proxy.HttpProxy;
            }

            var driver = new PhantomJSDriver(service)
            {
                Url = hostPgUrlPattern
            };

            driver.Navigate();
            var content = driver.PageSource;

            driver.Quit();

            return(content);
        }
        static int Main(string[] args)
        {
            if (args.Length == 0)
            {
                Console.WriteLine("You must provide the URL to unit test web page as the first command line argument");
                return(1);
            }

            string url = args[0];

            PhantomJSDriver driver = new PhantomJSDriver();

            try {
                IElementLocator locator = new QUnitElementLocator();
                JsTestRunner    runner  = new JsTestRunner(driver, locator);

                bool allTestsPassed = runner.ProcessAllTests(url);
                int  result         = allTestsPassed ? 0 : 1;

                return(result);
            }
            finally {
                driver.Quit();
                driver.Dispose();
            }
        }
Exemple #27
0
        public void TestPhantomJs()
        {
            IWebDriver driver = null;

            try
            {
                PhantomJSOptions options = new PhantomJSOptions();

                driver     = new PhantomJSDriver();
                driver.Url = "http://www.softpost.org";
                driver.Manage().Window.Maximize();
                Console.WriteLine("Title is " + driver.Title);

                driver.Navigate();
            }
            catch (Exception e)
            {
                Console.WriteLine("Exception ....*********" + e.ToString());
            }

            finally
            {
                Thread.Sleep(2000);
                driver.Close();
                driver.Quit();
            }
        }
Exemple #28
0
 static void Main(string[] args)
 {
     using (var driver = new PhantomJSDriver())
     {
         driver.Manage().Window.Maximize();
         var           saveDir = $"SaveImgs/";
         StringBuilder builder = new StringBuilder();
         foreach (var item in pagesConfig)
         {
             try
             {
                 Console.WriteLine($"开始前往{item.Key}首页:{item.Value}");
                 if (!Directory.Exists(saveDir))
                 {
                     Directory.CreateDirectory(saveDir);
                 }
                 driver.Navigate().GoToUrl(item.Value);
                 var saveName = $"{item.Key}.jpg";
                 var savePath = $"{ saveDir }/{ saveName}";
                 ((ITakesScreenshot)driver).GetScreenshot().SaveAsFile(savePath, ScreenshotImageFormat.Jpeg);
                 builder.AppendLine($"### {item.Key}");
                 builder.AppendLine($"![图片](./{saveName})");
                 Console.WriteLine($"图片保存至:{savePath}");
             }
             catch (Exception ex)
             {
                 Console.WriteLine(item.Key + "" + ex.Message);
             }
         }
         //创建MD文件
         Utils.FileHelper.WriteFile(builder.ToString(), $"{saveDir}/README.MD");
         driver.Quit();
     }
 }
Exemple #29
0
 public override void Dispose()
 {
     if (driver != null)
     {
         driver.Quit();
     }
     base.Dispose();
 }
Exemple #30
0
        public void CloseBrowser()
        {
            _logger.Trace("CloseBrowser");
            _driver?.Quit();
#if UseSeleniumWithGeckodriver
            _driver?.Dispose();//this is needed for close geckodriver.exe during closing application
#endif
        }