Ejemplo n.º 1
0
        public static Bitmap GetBitmap(Uri pageUrl)
        {
            if (driver == null)
            {
                Initialize();
            }

            driver.Navigate().GoToUrl(pageUrl);

            var screenshot = driver.GetScreenshot();
            var pageWidth  = (long)driver.ExecuteScript("return document.body.offsetWidth");
            var pageHeight = (long)driver.ExecuteScript("return document.body.offsetHeight");

            //Console.WriteLine("Page size: {0} x {1}", pageWidth, pageHeight);
            Bitmap screenshotBitmap = (Bitmap)Image.FromStream(new MemoryStream(screenshot.AsByteArray));
            var    gu       = GraphicsUnit.Pixel;
            var    ssBounds = screenshotBitmap.GetBounds(ref gu);

            var zoomLevel = (double)pageWidth / deviceOptions.Width;

            ssBounds.Height = Math.Min(ssBounds.Height, (float)Math.Floor(deviceOptions.PixelRatio * pageHeight / zoomLevel));

            var croppedScreenshot = screenshotBitmap.Clone(ssBounds, screenshotBitmap.PixelFormat);

            screenshotBitmap.Dispose();
            //croppedScreenshot.Save("C:/Users/fonsv/Desktop/hothothotcrop.png");
            //Console.WriteLine(driver.PageSource);

            return(croppedScreenshot);
        }
Ejemplo n.º 2
0
        public override async Task <TaskRes> Execute(HtmlDocument htmlDoc, ChromeDriver wb, Files.Models.AccModels.Account acc)
        {
            var mainBuilding = vill.Build.Buildings.FirstOrDefault(x => x.Type == Classificator.BuildingEnum.MainBuilding);

            if (mainBuilding == null)
            {
                return(TaskRes.Executed);
            }
            await acc.Wb.Navigate($"{acc.AccInfo.ServerUrl}/build.php?id={mainBuilding.Id}");

            if (vill.Build.DemolishTasks.Count == 0)
            {
                return(TaskRes.Executed);                                     //No more demolish tasks
            }
            var id = BuildingToDemolish(vill, htmlDoc);

            if (id == null)
            {
                return(TaskRes.Executed);            //No more demolish tasks
            }
            this.PostTaskCheck.Add(CheckDemolishTime);

            wb.ExecuteScript($"document.getElementById('demolish').value={id}");
            await Task.Delay(AccountHelper.Delay());

            wb.ExecuteScript($"document.getElementById('btn_demolish').click()");
            this.NextExecute = DateTime.Now.AddMinutes(10);
            return(TaskRes.Executed);
        }
Ejemplo n.º 3
0
        public override async Task <TaskRes> Execute(HtmlDocument htmlDoc, ChromeDriver wb, Files.Models.AccModels.Account acc)
        {
            if (!TaskExecutor.IsLoginScreen(acc))
            {
                await Task.Delay(AccountHelper.Delay() * 2);

                return(TaskRes.Executed);
            }

            var access = acc.Access.GetCurrentAccess();

            if (acc.AccInfo.ServerUrl.Contains("ttwars"))
            {
                wb.ExecuteScript($"document.getElementsByName('user')[0].value='{acc.AccInfo.Nickname}'");
                wb.ExecuteScript($"document.getElementsByName('pw')[0].value='{access.Password}'");
            }
            else
            {
                wb.ExecuteScript($"document.getElementsByName('name')[0].value='{acc.AccInfo.Nickname}'");
                wb.ExecuteScript($"document.getElementsByName('password')[0].value='{access.Password}'");
            }

            wb.ExecuteScript("document.getElementsByName('s1')[0].click()"); //Login button

            await Task.Delay(AccountHelper.Delay());

            htmlDoc.LoadHtml(acc.Wb.Driver.PageSource);
            if (TaskExecutor.IsLoginScreen(acc))
            {
                // Wrong password/nickname
                acc.TaskTimer.Stop();
            }
            return(TaskRes.Executed);
        }
Ejemplo n.º 4
0
        private static void TakeFullPageScreenshot(ChromeDriver driver, string url)
        {
            var name = new Uri(url).AbsolutePath.Replace('/', '_');

            //Dictionary will contain the parameters needed to get the full page screen shot
            var metrics = new Dictionary <string, object>
            {
                ["width"] = driver
                            .ExecuteScript("return Math.max(window.innerWidth,document.body.scrollWidth,document.documentElement.scrollWidth)"),
                ["height"] = driver
                             .ExecuteScript("return Math.max(window.innerHeight,document.body.scrollHeight,document.documentElement.scrollHeight)"),
                ["deviceScaleFactor"] = driver
                                        .ExecuteScript("return window.devicePixelRatio"),
                ["mobile"] = driver
                             .ExecuteScript("return typeof window.orientation !== 'undefined'")
            };

            //Execute the emulation Chrome Command to change browser to a custom device that is the size of the entire page
            driver.ExecuteChromeCommand("Emulation.setDeviceMetricsOverride", metrics);

            //Then just take screenshot as driver thinks that everything is visible
            var screenshot = driver.GetScreenshot();

            Console.WriteLine($"------------ Screenshot for \"{url}\" has been taken in thread {Task.CurrentId} ------------");

            //Save the screenshot
            screenshot.SaveAsFile(Path.Combine(CreateDirectory(_applicationSettings["DirectoryForScreenshots"]), $"{name}.jpg"));

            Console.WriteLine($"------------ Screenshot for \"{url}\" has been saved in thread {Task.CurrentId} ------------");

            //This command will return browser back to a normal, usable form if need to do anything else with it.
            driver.ExecuteChromeCommand("Emulation.clearDeviceMetricsOverride", new Dictionary <string, object>());
        }
Ejemplo n.º 5
0
 private void googlesearch()
 {
     drv.ExecuteScript("document.getElementsByClassName('gLFyf gsfi')[0].value='" + textBox8.Text + "';");
     drv.ExecuteScript("document.getElementsByClassName('gLFyf gsfi')[0].value='" + textBox8.Text + "';");
     drv.ExecuteScript("document.getElementsByClassName('gLFyf gsfi')[0].value='" + textBox8.Text + "';");
     drv.ExecuteScript("document.getElementsByClassName('gNO89b')[0].click();");
 }
Ejemplo n.º 6
0
        public void WaitForComplete()
        {
            EnsureDriver();
            var sw = new Stopwatch();

            try
            {
                Boolean readyState = false;
                do
                {
                    var rs = _driver.ExecuteScript("return window.__tests__ && window.__tests__.$isReady();");
                    Debug.WriteLine(rs);
                    if (rs is Boolean boolRs)
                    {
                        readyState = boolRs;
                    }
                    if (readyState)
                    {
                        Thread.Sleep(50);                         // Vue
                        return;
                    }
                    Thread.Sleep(20);
                    Debug.WriteLine("waiting...");
                    if (sw.ElapsedMilliseconds > WAIT_TIMEOUT)
                    {
                        throw new TimeoutException();
                    }
                } while (!readyState);
            }
            catch (Exception /*ex*/)
            {
                // do nothing
            }
        }
Ejemplo n.º 7
0
        static void Main(string[] args)
        {
            try
            {
                CloudStorageAccount storageAccount = CloudStorageAccount.Parse(ConfigurationManager.AppSettings["StorageConnectionString"].ToString());

                // Create a blob client for interacting with the blob service.
                blobClient    = storageAccount.CreateCloudBlobClient();
                blobContainer = blobClient.GetContainerReference(blobContainerName);
                blobContainer.CreateIfNotExists();
                blobContainer.SetPermissions(new BlobContainerPermissions {
                    PublicAccess = BlobContainerPublicAccessType.Blob
                });


                _chrome = new ChromeDriver(@"../../artifacts");
                _chrome.Manage().Window.Maximize();
                _chrome.Navigate().GoToUrl("https://login.xfinity.com/login");
                var username = _chrome.FindElementById("user");
                username.SendKeys(ConfigurationManager.AppSettings["username"]);
                var password = _chrome.FindElementById("passwd");
                password.SendKeys(ConfigurationManager.AppSettings["password"]);
                var submit = _chrome.FindElementById("sign_in");
                submit.Click();
                Console.WriteLine("Waiting on page to load");
                var wifiButton = WaitUntilElementExists("xfinity xfi");
                Console.WriteLine("navigating to devices");
                _chrome.Navigate().GoToUrl("https://internet.xfinity.com/devices");
                System.Threading.Thread.Sleep(10000);
                try
                {
                    Console.WriteLine("try to close tour popup");
                    _chrome.ExecuteScript("document.getElementById('tour').style.display = 'none';");
                }
                catch (Exception ex) {
                    Console.WriteLine("failed during js exectuion for closing tour popup");
                }
                System.Threading.Thread.Sleep(2000);
                try
                {
                    Console.WriteLine("try to close tour overlay");
                    _chrome.ExecuteScript("document.getElementsByClassName('ReactModal__Overlay')[0].style.display = 'none';");
                }
                catch (Exception ex) {
                    Console.WriteLine("failed during js exectuion for closing tour overlay");
                }

                System.Threading.Thread.Sleep(3000);
                Console.WriteLine("zoom out");
                _chrome.ExecuteScript("document.body.style.zoom='67%'");
                System.Threading.Thread.Sleep(1000);
                Console.WriteLine("take screen shot");
                TakeScreenShot();
                Console.WriteLine("finished");
            }
            catch (NoSuchElementException e) {
            }
            catch (Exception e) {
            }
        }
Ejemplo n.º 8
0
        private void PopulateBanList(ChromeDriver driver)
        {
            var firstListPost = driver.FindElementById("forum-post-body-2");

            driver.ExecuteScript("arguments[0].scrollIntoView();", firstListPost);
            var firstListTds = firstListPost.FindElements(By.XPath("//td"));

            foreach (var td in firstListTds)
            {
                driver.ExecuteScript("arguments[0].scrollIntoView();", td);
                if (string.IsNullOrEmpty(td.Text))
                {
                    continue;
                }
                if (td.Text != "-")
                {
                    var banName = td.Text.Split('#');
                    _banList.Add($"{banName[0]}{banName[1]}");
                    _banList.Add($"{banName[0]}#{banName[1]}");
                    _banList.Add($"{banName[0]} {banName[1]}");
                    _banList.Add($"{banName[0]} #{banName[1]}");
                    _banList.Add($"{banName[0]} # {banName[1]}");
                    _banList.Add($"{banName[0]}# {banName[1]}");
                }
            }
        }
Ejemplo n.º 9
0
 public void OpenNewTabPage(string url)
 {
     WebDriver.ExecuteScript("window.open();");
     WebDriver.SwitchTo().Window(WebDriver.WindowHandles.Last());
     WebDriver.Navigate().GoToUrl(url);
     Wait(2);
 }
        public static string Capture(ChromeDriver driver)
        {
            //Dictionary will contain the parameters needed to get the full page screen shot
            Dictionary <string, Object> metrics = new Dictionary <string, Object>();

            metrics["width"]             = driver.ExecuteScript("return Math.max(window.innerWidth,document.body.scrollWidth,document.documentElement.scrollWidth)");
            metrics["height"]            = driver.ExecuteScript("return Math.max(window.innerHeight,document.body.scrollHeight,document.documentElement.scrollHeight)");
            metrics["deviceScaleFactor"] = (double)driver.ExecuteScript("return window.devicePixelRatio");
            metrics["mobile"]            = driver.ExecuteScript("return typeof window.orientation !== 'undefined'");
            //Execute the emulation Chrome Command to change browser to a custom device that is the size of the entire page
            driver.ExecuteChromeCommand("Emulation.setDeviceMetricsOverride", metrics);

            DateTime         time       = DateTime.Now;
            String           fileName   = "Screenshot_" + time.ToString("h_mm_ss") + ".png";
            ITakesScreenshot ts         = (ITakesScreenshot)driver;
            Screenshot       screenshot = ts.GetScreenshot();
            var pth        = System.Reflection.Assembly.GetCallingAssembly().CodeBase;
            var actualPath = pth.Substring(0, pth.LastIndexOf("bin"));
            var reportPath = new Uri(actualPath).LocalPath;

            Directory.CreateDirectory(reportPath + "Reports\\" + "Screenshots");
            var finalpth  = pth.Substring(0, pth.LastIndexOf("bin")) + "Reports\\Screenshots\\" + fileName;
            var localpath = new Uri(finalpth).LocalPath;

            screenshot.SaveAsFile(localpath, ScreenshotImageFormat.Png);
            //This command will return your browser back to a normal, usable form if you need to do anything else with it.
            driver.ExecuteChromeCommand("Emulation.clearDeviceMetricsOverride", new Dictionary <string, Object>());
            return(localpath);
        }
Ejemplo n.º 11
0
        //TODO Add options for catapult/scout targets inside SendTroops2!

        public override async Task <TaskRes> Execute(HtmlDocument htmlDoc, ChromeDriver wb, Files.Models.AccModels.Account acc)
        {
            await acc.Wb.Navigate($"{acc.AccInfo.ServerUrl}/build.php?tt=2&id=39");

            //add number of troops to the input boxes
            for (int i = 0; i < TroopsMovement.Troops.Length; i++)
            {
                if (TroopsMovement.Troops[i] == 0)
                {
                    continue;
                }
                wb.ExecuteScript($"document.getElementsByName('t{i + 1 }')[0].value='{TroopsMovement.Troops[i]}'");
                await Task.Delay(222);
            }

            //select coordinates
            wb.ExecuteScript($"document.getElementById('xCoordInput').value='{TroopsMovement.Coordinates.x}'");
            wb.ExecuteScript($"document.getElementById('yCoordInput').value='{TroopsMovement.Coordinates.y}'");
            await Task.Delay(AccountHelper.Delay());

            //Select type of troop sending
            string script = "var radio = document.getElementsByClassName(\"radio\");for(var i = 0; i < radio.length; i++){";

            script += $"if(radio[i].value == \"{(int)TroopsMovement.MovementType}\") radio[i].checked = \"checked\"}}";
            wb.ExecuteScript(script);
            await Task.Delay(2 *AccountHelper.Delay());

            //Click on "Send" button
            wb.ExecuteScript($"document.getElementById('btn_ok').click()");

            return(TaskRes.Executed);
        }
Ejemplo n.º 12
0
        public static string GetCookies(HttpWebResponse httpWebResponse)
        {
            var script1      = "";
            var script2      = "";
            var chromeDriver = new ChromeDriver();

            try
            {
                using (var responseStream = httpWebResponse.GetResponseStream())
                    using (var streamReader = new StreamReader(responseStream ?? throw new InvalidOperationException(), Encoding.UTF8))
                        script1 = streamReader.ReadToEnd();
                chromeDriver.Navigate().GoToUrl(httpWebResponse.ResponseUri);
                var run = script1.Substring("<script>", "</script>").Replace("{eval(", "{return (");
                run     = $"function script2(){{{run}}}; return script2();";
                script2 = chromeDriver.ExecuteScript(run).ToString();
                var del = script2.Substring("=function(){", "document.cookie=");
                run = script2.Replace(del + "document.cookie=", "return ");
                var name = script2.Substring("var ", "=");
                run = $"{run}; return {name}();";
                var cookie = chromeDriver.ExecuteScript(run).ToString();
                return(cookie);
            }
            catch (Exception ex)
            {
                ex.SendCodeSite();
                CodeSite.Send("script1", script1);
                CodeSite.Send("script2", script2);
                return("");
            }
            finally
            {
                chromeDriver.Quit();
            }
        }
Ejemplo n.º 13
0
        public override async Task <TaskRes> Execute(HtmlDocument htmlDoc, ChromeDriver wb, Files.Models.AccModels.Account acc)
        {
            var building = vill.Build.Buildings.FirstOrDefault(x => x.Type == Classificator.BuildingEnum.Residence || x.Type == Classificator.BuildingEnum.Palace || x.Type == Classificator.BuildingEnum.CommandCenter);

            if (building == null)
            {
                //update dorg, no buildingId found?
                TaskExecutor.AddTask(acc, new UpdateDorf2()
                {
                    ExecuteAt = DateTime.Now, vill = vill
                });
                Console.WriteLine($"There is no Residence/Palace/CommandCenter in this village!");
                return(TaskRes.Executed);
            }
            await acc.Wb.Navigate($"{acc.AccInfo.ServerUrl}/build.php?s=1&id={building.Id}");

            var cost = htmlDoc.DocumentNode.Descendants("div").FirstOrDefault(x => x.HasClass("resourceWrapper"));

            if (cost == null)
            {
                this.ErrorMessage = "Could not train settlers. Will retry in 5min";
                this.NextExecute  = DateTime.Now.AddMinutes(5); //retry in 5min
                return(TaskRes.Executed);
            }

            var resources   = ResourceParser.GetResourceCost(cost);
            var enoughResAt = ResourcesHelper.EnoughResourcesOrTransit(acc, vill, resources);

            if (enoughResAt <= DateTime.Now.AddMilliseconds(1)) //we have enough res, create new settler!
            {
                wb.ExecuteScript($"document.getElementsByName('t10')[0].value='1'");
                await Task.Delay(AccountHelper.Delay());

                wb.ExecuteScript($"document.getElementById('s1').click()"); //Train settler
                vill.Troops.Settlers++;
                if (vill.Troops.Settlers < 3)
                {
                    //In 1 minute, do the same task (to get total of 3 settlers)
                    this.NextExecute = DateTime.Now.AddSeconds(1);
                }
                else
                {
                    if (acc.NewVillages.AutoSettleNewVillages)
                    {
                        //parse in training table
                        this.PostTaskCheck.Add(NewVillage);
                    }
                }
                return(TaskRes.Executed);
            }
            else
            {
                //Not enough res, wait for production/transit res
                this.NextExecute = enoughResAt.AddSeconds(60 * AccountHelper.Delay());
                return(TaskRes.Executed);
            }
        }
Ejemplo n.º 14
0
        public override async Task <TaskRes> Execute(HtmlDocument htmlDoc, ChromeDriver wb, Files.Models.AccModels.Account acc)
        {
            if (vill == null)
            {
                vill = AccountHelper.GetMainVillage(acc);
            }

            Classificator.BuildingEnum building = (Great == false) ? TroopsHelper.GetTroopBuilding(troop, false) : TroopsHelper.GetTroopBuilding(troop, true);

            var buildId = vill.Build.Buildings.FirstOrDefault(x => x.Type == building);

            if (buildId == null)
            {
                //update dorf, no buildingId found?
                TaskExecutor.AddTask(acc, new UpdateDorf2()
                {
                    ExecuteAt = DateTime.Now
                });
                Console.WriteLine($"There is no {building} in this village!");
                return(TaskRes.Executed);
            }
            await acc.Wb.Navigate($"{acc.AccInfo.ServerUrl}/build.php?id={buildId.Id}");

            var troopNode = htmlDoc.DocumentNode.Descendants("img").FirstOrDefault(x => x.HasClass("u" + (int)troop));

            while (!troopNode.HasClass("details"))
            {
                troopNode = troopNode.ParentNode;
            }

            //finding the correct "Exchange resources" button
            var exchangeResButton = troopNode.Descendants("button").FirstOrDefault(x => x.HasClass("gold"));

            wb.ExecuteScript($"document.getElementById('{exchangeResButton.GetAttributeValue("id", "")}').click()"); //Exchange resources button

            await Task.Delay(AccountHelper.Delay());

            htmlDoc.LoadHtml(wb.PageSource);
            await Task.Delay(AccountHelper.Delay());

            var distribute = htmlDoc.DocumentNode.SelectNodes("//*[text()[contains(., 'Distribute remaining resources.')]]")[0];

            while (distribute.Name != "button")
            {
                distribute = distribute.ParentNode;
            }
            string distributeid = distribute.GetAttributeValue("id", "");

            wb.ExecuteScript($"document.getElementById('{distributeid}').click()"); //Distribute resources button

            await Task.Delay(AccountHelper.Delay());

            wb.ExecuteScript($"document.getElementById('npc_market_button').click()"); //Exchange resources button

            return(TaskRes.Executed);
        }
Ejemplo n.º 15
0
 public bool ExecuteScript(string script)
 {
     try {
         _cd.ExecuteScript(script);
         return(true);
     } catch (WebDriverException e) {
         _l.error(e.Message);
         return(false);
     }
 }
Ejemplo n.º 16
0
        void Login()
        {
            driver.Url = "https://tweetdeck.twitter.com";
            WaitUntilLoadOne(By.TagName("a")).Click();

            Thread.Sleep(500);
            WaitUntilLoadOne(By.ClassName("js-username-field"));

            driver.ExecuteScript($"document.getElementsByClassName('js-username-field')[0].value='{Settings.Default.USERNAME}'");
            driver.ExecuteScript($"document.getElementsByClassName('js-password-field')[0].value='{Settings.Default.PASSWORD}'");
            driver.ExecuteScript($"document.getElementsByClassName('submit')[1].click()");
        }
Ejemplo n.º 17
0
 private static void BreakSite(ChromeDriver driver)
 {
     driver.ExecuteScript("arguments[0].setAttribute('style','color: red')",
                          driver.FindElement(By.CssSelector("#login > form > div.auth-form-body.mt-3 > label:nth-child(1)")));
     driver.ExecuteScript("arguments[0].setAttribute('style','color: pink')",
                          driver.FindElement(By.CssSelector("#login > form > div.auth-form-body.mt-3 > label:nth-child(3)")));
     driver.ExecuteScript("arguments[0].setAttribute('style','fill: green')",
                          driver.FindElement(By.CssSelector(
                                                 "body > div.position-relative.js-header-wrapper > div.header.header-logged-out.width-full.pt-5.pb-4 > div > a > svg")));
     driver.ExecuteScript("arguments[0].setAttribute('style','font-size: 8px')",
                          driver.FindElement(By.CssSelector("#login > p")));
 }
        public async Task Browse(Credential credential, Guid sourceId)
        {
            var driver = new ChromeDriver(new ChromeOptions {
                PageLoadStrategy = PageLoadStrategy.Eager
            });
            WebDriverWait _wait = new WebDriverWait(driver, new TimeSpan(0, 0, 10));

            try {
                driver.Navigate().GoToUrl("https://www.linkedin.com/login");
                driver.ExecuteScript("console.log('hi!')");
                _wait.Until(d => d.FindElement(By.Id("username")));
                driver.FindElement(By.Id("username")).SendKeys(credential.ExternalIdentifier);
                var passwordTextfield = driver.FindElement(By.Id("password"));
                passwordTextfield.SendKeys(credential.ExternalSecret);
                var button = driver.FindElement(By.CssSelector("button[aria-label='Sign in']"));
                button.Click();
                await Task.Delay(1000);

                driver.Navigate().GoToUrl("https://www.linkedin.com/mynetwork/invite-connect/connections/");
                driver.ExecuteScript(RECORD_XHR_BLOBS);

                _wait.Until(d => d.FindElement(By.CssSelector("[aria-label='Sorting options for connections list']")));
                var dropdown = driver.FindElement(By.CssSelector("[aria-label='Sorting options for connections list']"));
                dropdown.Click();
                driver.FindElement(By.CssSelector("[data-control-name='sort_by_recently_added']")).Click();

                _wait.Until(ExpectedConditions.ElementExists(By.CssSelector("button[aria-label^='Send message']")));
                var connections      = driver.FindElementsByClassName("mn-connection-card");
                var totalConnections = connections.Count;
                for (int i = 0; i < connections.Count; i++)
                {
                    var connection = connections[i];
                    var card       = new ConnectionCard(connection);
                    driver.ExecuteScript("arguments[0].scrollIntoView()", connection);

                    var received = new Events.User {
                        AvatarUrl = card.MugshotUrl, Description = card.Occupation, Id = card.ProfileUrl.AsId <User>(Network.LinkedIn), KnownSince =
                            card.ConnectedDate, Name = card.Name, Network = Network.LinkedIn
                    };
                    connections = driver.FindElementsByClassName("mn-connection-card");
                    var responses = driver.ExecuteScript("return window.lresponses;");
                    driver.ExecuteScript("window.lresponses.clear();");
                    await SaveResponses(credential, sourceId, responses);
                }
            }
            catch (Exception e) {
                _logger.LogError(e, "Failed");
            }
            finally {
                driver?.Quit();
            }
        }
Ejemplo n.º 19
0
        public void ExecuteScriptTest()
        {
            using (var driver = new ChromeDriver(@"D:\WebDriver\bin")) //声明chrome驱动器
            {
                driver.Navigate().GoToUrl("https://cn.bing.com/");

                driver.ExecuteScript("window.open('http://www.baidu.com','_blank');");

                string text = (string)driver.ExecuteScript("return document.title");

                Thread.Sleep(3000);
            }
        }
Ejemplo n.º 20
0
        private void OpenUserInNewTab()
        {
            var nextUser = GetNextUser();

            if (nextUser == null)
            {
                Helpers.Print("Job Done", ConsoleColor.DarkRed);
                return;
            }

            _driver.ExecuteScript("window.open('about:blank', '-blank')");
            _driver.SwitchTo().Window(_driver.WindowHandles[1]);
            _driver.Url = nextUser;
        }
        public void Given_a_blazor_app_When_passing_anonymous_argument_Then_should_serialize_and_execute()
        {
            _driver.Navigate().GoToUrl("http://localhost:54235");

            object actual = null;

            SpinWait.SpinUntil(() =>
            {
                actual = _driver.ExecuteScript("return JSON.stringify(JsInterop.anonymous)");
                return(actual != null && actual.ToString() != "null");
            }, TimeSpan.FromSeconds(2));

            Assert.Equal("{\"property\":\"Value\",\"field\":123,\"child\":{\"member\":\"2001-01-01T00:00:00\"}}", actual);
        }
Ejemplo n.º 22
0
        private static void Login(ChromeDriver driver)
        {
            // driver.FindElement(By.Id("btn_Login")).GetAttribute("value");
            //2.执行 js 获取 value 的值
            //driver.ExecuteScript("return document.getElementsById('txt_AccountId')[0].value;");
            driver.ExecuteScript("return $('#帐号输入框ID').val('账号')"); //账号密码
            driver.ExecuteScript("return $('#密码输入框ID').val('密码')");
            // 3.执行jQuery 获取 value 的值
            var account = driver.ExecuteScript("return $('#帐号输入框ID').val()");
            var pass    = driver.ExecuteScript("return $('#密码输入框ID').val()");

            driver.FindElement(By.Id("登录按钮ID")).Click(); //点击登录
            Thread.Sleep(1000);                          // 给点时间加载网页
        }
Ejemplo n.º 23
0
        public void SteamGuard()
        {
            if (_status == "Disabling Steamguard")
            {
                try
                {
                    ChromeDriverService service = ChromeDriverService.CreateDefaultService();
                    service.HideCommandPromptWindow = true;

                    var options = new ChromeOptions();
                    options.AddArgument("headless");
                    options.AddArgument("--window-position=-32000,-32000");

                    var driver = new ChromeDriver(service, options);
                    try
                    {
                        driver.Navigate().GoToUrl("https://store.steampowered.com/login/?redir=twofactor%2Fmanage");
                        delay(2000);
                        driver.ExecuteScript("document.getElementById('input_username').value = '" + _alias + "'");
                        driver.ExecuteScript("document.getElementById('input_password').value = '" + _pass + "'");
                        delay(1000);
                        driver.ExecuteScript("document.querySelector('.btnv6_blue_hoverfade.btn_medium').click()");
                        delay(4000);
                        driver.ExecuteScript("document.forms['none_authenticator_form'].submit()");
                    }
                    catch
                    {
                        _status = "Couldn't Disable Steamguard"; UpdateStatus();
                        delay(1000);
                    }
                    try
                    {
                        driver.ExecuteScript("document.getElementById('none_authenticator_form').submit()");
                        delay(3000);
                        _status = "Finished";
                        UpdateStatus();
                    }
                    catch { _status = "Couldn't Disable Steamguard"; UpdateStatus(); }
                    driver.Quit();
                }
                catch
                {
                }
            }
            else
            {
                _status = "Couldn't Disable SteamGuard"; UpdateStatus();
            }
        }
Ejemplo n.º 24
0
        public override async Task <TaskRes> Execute(HtmlDocument htmlDoc, ChromeDriver wb, Files.Models.AccModels.Account acc)
        {
            await acc.Wb.Navigate($"{acc.AccInfo.ServerUrl}/dorf2.php");

            Random rnd = new Random();
            int    sec = rnd.Next(370, 380);

            TaskExecutor.AddTask(acc, new TTWarsGetRes()
            {
                ExecuteAt = DateTime.Now.AddSeconds(sec), vill = AccountHelper.GetMainVillage(acc)
            });
            TaskExecutor.AddTask(acc, new TrainExchangeRes()
            {
                ExecuteAt = DateTime.Now.AddSeconds(sec + 5), troop = acc.Villages[0].Troops.TroopToTrain ?? Classificator.TroopsEnum.Hero, vill = vill
            });
            TaskExecutor.AddTask(acc, new TrainTroops()
            {
                ExecuteAt       = DateTime.Now.AddSeconds(sec + 9),
                Troop           = acc.Villages[0].Troops.TroopToTrain ?? Classificator.TroopsEnum.Hero,
                vill            = vill,
                HighSpeedServer = true
            });


            wb.ExecuteScript("window.fireEvent('startPaymentWizard', {data:{activeTab: 'paymentFeatures'}});");

            await Task.Delay(AccountHelper.Delay() * 2);

            wb.ExecuteScript("$$('.paymentWizardMenu').addClass('hide');$$('.buyGoldInfoStep').removeClass('active');$$('.buyGoldInfoStep#2').addClass('active');$$('.paymentWizardMenu#buyResources').removeClass('hide');"); //Excgabge resources button

            await Task.Delay(AccountHelper.Delay() * 2);

            htmlDoc.LoadHtml(wb.PageSource);

            //gold prosButton buyResources6
            //gold prosButton buyAnimal5
            var buy = htmlDoc.DocumentNode.Descendants("button").FirstOrDefault(x => x.HasClass("buyResources6"));

            if (buy == null)
            {
                this.ErrorMessage = "Can't find the button with class buyResources6. Are you sure you are on vip/unl TTWars server?";
                return(TaskRes.Executed);
            }
            var buyId = buy.GetAttributeValue("id", "");

            wb.ExecuteScript($"document.getElementById('{buyId}').click()");
            return(TaskRes.Executed);
        }
Ejemplo n.º 25
0
        public static String GetValue(this IWebElement element, ChromeDriver driver = null, String attribute = "", String defaultValue = "")
        {
            String value = defaultValue;

            if (String.IsNullOrEmpty(attribute))
            {
                if (!element.Displayed && driver != null)
                {
                    value = driver.ExecuteScript("return arguments[0].textContent", element).ToString();
                }
                else
                {
                    value = element.Text;
                }
            }
            else
            {
                value = element.GetAttribute(attribute);
            }
            if (!String.IsNullOrEmpty(value))
            {
                value = WebExtension.DecodeHtml(value);
                value = WebExtension.DecodeUrl(value);
            }
            return(value);
        }
Ejemplo n.º 26
0
        int i = 0;                         // 현재 배열 위치
        private void btnSearch_Click(object sender, EventArgs e)
        {
            string strUrl = "https://www.google.com/search?q=" + txtSearch.Text + "&source=lnms&tbm=isch";

            _driver = new ChromeDriver(_driverService, _options);
            _driver.Navigate().GoToUrl(strUrl);
            _driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(10);

            _driver.ExecuteScript("window.scrollBy(0,10000)");      // 창을 띄우고 스크롤 진행(아래 스크롤 한거)

            lstSrc = new List <string>();

            foreach (IWebElement item in _driver.FindElementsByClassName("rg_i"))
            {
                if (item.GetAttribute("src") != null)
                {
                    lstSrc.Add(item.GetAttribute("src"));
                }
            }

            lblTotal.Text = string.Format("/ {0}", lstSrc.Count);

            this.Invoke(new Action(delegate()
            {
                foreach (string strsrc in lstSrc)
                {
                    i++;
                    GetMapImage(lstSrc[i]);
                    txtGo.Text = i.ToString();
                    Refresh();
                    Thread.Sleep(50);
                }
            }));
        }
Ejemplo n.º 27
0
        public CloudFlareServiceSelenium(IConfiguration configuration, ILogger <CloudFlareServiceSelenium> logger)
        {
            _logger = logger;
            var userAgent = RandomUserAgent.Generate();

            _logger.LogInformation($"Initialize Chrome driver with userAgent: {userAgent}");
            var chromeOptions = new ChromeOptions();

            if (configuration.IsHeadless())
            {
                chromeOptions.AddArguments("headless");
                _logger.LogInformation("Enable Headless mode");
            }

            chromeOptions.AddExcludedArgument("enable-automation");
            chromeOptions.AddAdditionalCapability("useAutomationExtension", false);
            chromeOptions.AddArgument("--disable-blink-features=AutomationControlled");
            chromeOptions.AddArgument("--lang=en-US");
            _driver = new ChromeDriver(chromeOptions);
            _driver.ExecuteScript("Object.defineProperty(navigator, 'webdriver', {get: () => undefined})");
            _driver.ExecuteChromeCommand("Network.setUserAgentOverride", new Dictionary <string, object>
            {
                { "userAgent", userAgent }
            });
            _driver.Navigate().GoToUrl(CloudFlareLoginUrl);
            _waiter = new WebDriverWait(_driver, TimeSpan.FromMinutes(3));
        }
Ejemplo n.º 28
0
        public static string ScrollToEnd(string url)
        {
            ChromeOptions chromeOptions = new ChromeOptions();

            chromeOptions.AddArgument("--disable-images");
            string       directory    = @"C:\Users\Edvin\source\repos\edvinhakobyan\Json_Serialization\WorkingHTMLData\WorkingHTMLData\bin\Debug";
            ChromeDriver chromeDriver = new ChromeDriver(directory, chromeOptions);

            chromeDriver.Navigate().GoToUrl(url);

            for (int i = 0; i < 10; i++)
            {
                try
                {
                    chromeDriver.ExecuteScript($"window.scrollBy(0,1750);");
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                }
                Thread.Sleep(2000);
            }

            string returnVaule = chromeDriver.PageSource;

            chromeDriver.Close();
            return(returnVaule);
        }
Ejemplo n.º 29
0
        public async Task InitCafeInfo()
        {
            _driver.Url = GetCafeUrlFromName(Name);
            await Task.Delay(bigDelay);

            clubId = _driver.ExecuteScript("return g_sClubId").ToString();
        }
        public void Taxcom()
        {
            ChromeOptions options = new ChromeOptions();

            options.EnableMobileEmulation("iPhone 6");
            var driver = new ChromeDriver(options);

            var eyes = new Eyes();

            eyes.SetLogHandler(new StdoutLogHandler(true));
            //eyes.StitchMode = StitchModes.CSS;
            eyes.MatchTimeout = TimeSpan.FromSeconds(0);
            eyes.StitchMode   = StitchModes.Scroll;
            //eyes.SendDom = false;

            driver.Url = "https://taxcom.ru/centr/";

            try
            {
                eyes.WaitBeforeScreenshots = 600;
                var eyesDriver = eyes.Open(driver, "Taxcom", "#29531");
                driver.ExecuteScript("document.querySelector('a.scrollToTop').style.visibility='hidden'");
                eyes.Check(Target.Window().Fully());
                eyes.Close();
            }
            finally
            {
                driver.Quit();
                eyes.AbortIfNotClosed();
            }
        }