예제 #1
0
        public void AddCookie(Cookie cookie)
        {
            var MRes = new ManualResetEventSlim(true);

            MRes.Reset();
            Exception exception = null;

            Task.Run(async() =>
            {
                try
                {
                    await cookies.AddCookie(cookie).ConfigureAwait(false);
                    MRes.Set();
                }
                catch (Exception ex)
                {
                    exception = ex;
                }
            }

                     );
            MRes.Wait();
            if (exception != null)
            {
                throw exception;
            }
        }
예제 #2
0
 /// <summary>
 /// Adds a cookie to the browser
 /// </summary>
 /// <param name="name">The name of the cookie to add</param>
 /// <param name="value">The value set within the cookie</param>
 public void AddCookie(string name, string value)
 {
     try
     {
         if (typeof(TWebDriver) != typeof(InternetExplorerDriver))
         {
             Driver.Manage().Cookies.AddCookie(new Cookie(name, value));
         }
         else if (typeof(TWebDriver) == typeof(InternetExplorerDriver))
         {
             string script = "document.cookie='" + name + "=" + value + "'";
             Driver.ExecuteJavaScript(script);
         }
         else
         {
             ICookieJar cookieJar = Driver.Manage().Cookies;
             cookieJar.AddCookie(new Cookie(name, value));
         }
         Console.Out.WriteLine("Cookie {0} has been added with a value {1}.", name, value);
     }
     catch (Exception ex)
     {
         if (ex.GetType() == typeof(UnableToSetCookieException))
         {
             Console.Out.WriteLine("Unable to set the cookie {0} as requested", name);
             if (Driver.Url == null)
             {
                 Console.Out.WriteLine("The driver is not currently set with a URL");
             }
         }
         HandleErrors(ex);
     }
 }
        public void AddCookie(CookieInstance cookie)
        {
            if (cookie == null)
            {
                return;
            }

            m_cookieJar.AddCookie(cookie.Cookie);
        }
예제 #4
0
        public static void addCookieByByte(byte[] arrByte, IWebDriver oIWebDriver)
        {
            var lstCookieEx = (List <Dictionary <string, object> >)SerialUtilsEx.deserializeObject(arrByte);

            foreach (var mapCookie in lstCookieEx)
            {
                var        oCookie     = Cookie.FromDictionary(mapCookie);
                ICookieJar oICookieJar = oIWebDriver.Manage().Cookies;
                oICookieJar.AddCookie(oCookie);
            }
        }
예제 #5
0
        public static void AddCookies(IWebDriver webDriver, CookieCollection Coookie)
        {
            DateTime   now;
            ICookieJar listCookie = webDriver.Manage().Cookies;

            foreach (System.Net.Cookie item in Coookie)
            {
                OpenQA.Selenium.Cookie yuan = listCookie.GetCookieNamed(item.Name);
                if (yuan == null)
                {
                    item.Domain  = ".huya.com";
                    now          = DateTime.Now;
                    item.Expires = now.AddDays(365);
                }
                else
                {
                    if (!yuan.Expiry.HasValue)
                    {
                        now          = DateTime.Now;
                        item.Expires = now.AddDays(365);
                    }
                    else
                    {
                        item.Expires = yuan.Expiry.Value;
                    }
                    item.Domain = yuan.Domain;
                    listCookie.DeleteCookieNamed(yuan.Name);
                }
                try
                {
                    OpenQA.Selenium.Cookie newCookie = new OpenQA.Selenium.Cookie(item.Name, item.Value, item.Domain, "/", new DateTime?(item.Expires));
                    listCookie.AddCookie(newCookie);
                }
                catch (Exception exception)
                {
                    XTrace.WriteLine(string.Concat("设置cookie 出错 ", exception.Message));
                }
            }
        }
    static void Main(string[] args)
    {
        string        executablePath = null;
        string        executableName = null;
        bool          useService     = false;
        Uri           remotePort     = null;
        ChromeOptions chromeOptions  = new ChromeOptions();
        string        logPath        = null;
        string        url            = "http://www.google.com/";
        string        htmlPath       = null;
        bool          append         = false;
        bool          name           = false;
        bool          title          = false;
        bool          quit           = true;
        bool          testCookies    = false;
        bool          testPosition   = false;
        bool          testSize       = false;

        for (int argi = 0; argi < args.Length; argi++)
        {
            if (!args[argi].StartsWith("-"))
            {
                Usage();
            }

            if (args[argi] == "-driver" && argi + 1 < args.Length)
            {
                executablePath = Path.GetFullPath(args[++argi]);
                if (File.Exists(executablePath))
                {
                    executableName = Path.GetFileName(executablePath);
                    executablePath = Path.GetDirectoryName(executablePath);
                }
            }
            else if (args[argi] == "-chrome" && argi + 1 < args.Length)
            {
                chromeOptions.BinaryLocation = args[++argi];
            }
            else if (args[argi] == "-data" && argi + 1 < args.Length)
            {
                chromeOptions.AddArgument("user-data-dir=" + args[++argi]);
            }
            else if (args[argi] == "-service")
            {
                useService = true;
            }
            else if (args[argi] == "-remote" && argi + 1 < args.Length)
            {
                remotePort = new Uri(args[++argi]);
            }
            else if (args[argi] == "-url" && argi + 1 < args.Length)
            {
                url = args[++argi];
            }
            else if (args[argi] == "-log" && argi + 1 < args.Length)
            {
                logPath = args[++argi];
            }
            else if (args[argi] == "-append")
            {
                append = true;
            }
            else if (args[argi] == "-save" && argi + 1 < args.Length)
            {
                htmlPath = args[++argi];
            }
            else if (args[argi] == "-debug" && argi + 1 < args.Length)
            {
                // Chrome should have been started with --remote-debugging-port=port
                chromeOptions.DebuggerAddress = args[++argi];
            }
            else if (args[argi] == "-name")
            {
                name = true;
            }
            else if (args[argi] == "-title")
            {
                title = true;
            }
            else if (args[argi] == "-cookies")
            {
                testCookies = true;
            }
            else if (args[argi] == "-position")
            {
                testPosition = true;
            }
            else if (args[argi] == "-size")
            {
                testSize = true;
            }
            else if (args[argi] == "-keep")
            {
                quit = false;
            }
            else
            {
                Usage();
            }
        }

        if (useService && remotePort != null)
        {
            Console.Error.WriteLine("Can't use both -service and -remote options");
            Environment.Exit(1);
        }

        ChromeDriverService service =
            executablePath == null?ChromeDriverService.CreateDefaultService() :
                executableName == null?ChromeDriverService.CreateDefaultService(executablePath) :
                    ChromeDriverService.CreateDefaultService(executablePath, executableName);

        if (logPath != null)
        {
            service.LogPath = logPath;
            service.EnableVerboseLogging = true;
        }

        if (append)
        {
            service.EnableAppendLog = true;
        }

        if (useService)
        {
            service.Start();
            remotePort = service.ServiceUrl;
            Console.WriteLine("Service URL: {0}", remotePort);
        }

        RemoteWebDriver driver;

        if (remotePort != null)
        {
            driver = new RemoteWebDriver(remotePort, chromeOptions);
        }
        else
        {
            driver = new ChromeDriver(service, chromeOptions);
        }

        if (name)
        {
            Console.WriteLine("Browser name: {0}", driver.Capabilities.GetCapability("browserName"));
        }

        driver.Navigate().GoToUrl(url);

        if (title)
        {
            Console.WriteLine("Page title: {0}", driver.Title);
            Console.WriteLine("Page URL: {0}", driver.Url);
        }

        if (htmlPath != null)
        {
            using (TextWriter f = File.CreateText(htmlPath))
            {
                f.Write(driver.PageSource);
            }
        }

        if (testCookies)
        {
            ICookieJar cookieJar = driver.Manage().Cookies;
            cookieJar.AddCookie(new Cookie("foo", "bar", "/"));
            Console.WriteLine("Cookies:");
            foreach (Cookie cookie in cookieJar.AllCookies)
            {
                Console.WriteLine("\t{0}", cookie);
            }
        }

        if (testPosition)
        {
            IWindow window   = driver.Manage().Window;
            Point   position = window.Position;
            int     x        = position.X;
            int     y        = position.Y;
            Console.WriteLine("Current window position ({0}, {1})", x, y);

            x += 100;
            y += 100;
            Console.WriteLine("Attempting to change window position to ({0}, {1})", x, y);
            window.Position = new Point(x, y);

            position = window.Position;
            Console.WriteLine("New window position ({0}, {1})", position.X, position.Y);
        }

        if (testSize)
        {
            IWindow window = driver.Manage().Window;
            Size    size   = window.Size;
            int     width  = size.Width;
            int     height = size.Height;
            Console.WriteLine("Current window size {0}x{1}", width, height);

            width  /= 2;
            height /= 2;
            Console.WriteLine("Attempting to change window size to {0}x{1}", width, height);
            window.Size = new Size(width, height);

            size = window.Size;
            Console.WriteLine("New window size {0}x{1}", size.Width, size.Height);
        }

        if (quit)
        {
            Thread.Sleep(3000);
            driver.Quit();
        }
    }
예제 #7
0
 public void AddCookie(Cookie cookie)
 {
     _cookieJar.AddCookie(cookie);
 }
예제 #8
0
        static bool ErrorCheck      = false;     //若錯誤,一直重新整理

        static void Main(string[] args)
        {
            //關閉Chrome彈出的訊息通知
            ChromeOptions options = new ChromeOptions();

            //options.AddArguments("headless");                     //無頭模式(無瀏覽器畫面)
            options.AddArguments("--disable-notifications");     //關閉Chrome內建的提示
            options.AddArguments("--ignore-certificate-errors"); //關閉ERROR:ssl_client_socket_impl.cc(1098)訊息

            driver = new ChromeDriver(options);                  //將關閉通知的設定寫入到Chrome裡面
            //driver.Url = "https://tixcraft.com/activity/detail/19_MAROON5";
            driver.Url = "https://tixcraft.com/activity/detail/19_JOKERXUE";
            //driver.Url = "https://tixcraft.com/activity/detail/19_YJS";

            //driver.Manage().Window.Maximize();                //視窗最大化
            driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(2);  //隱性等待,主要是網頁的完整性,拿掉會錯誤

            //Cookie紀錄管理,將資料寫入cookie登入系統
            ICookieJar listcookie = driver.Manage().Cookies;

            #region 會員Cookie寫入,需自己填入在參數2那邊
            OpenQA.Selenium.Cookie newCookie0 = new OpenQA.Selenium.Cookie("_ga", "", "", DateTime.Now.AddDays(1));
            OpenQA.Selenium.Cookie newCookie1 = new OpenQA.Selenium.Cookie("_gid", "", "", DateTime.Now.AddDays(1));
            OpenQA.Selenium.Cookie newCookie2 = new OpenQA.Selenium.Cookie("CSRFTOKEN", "", "", DateTime.Now.AddDays(1));
            OpenQA.Selenium.Cookie newCookie3 = new OpenQA.Selenium.Cookie("_gat", "", "", DateTime.Now.AddDays(1));
            OpenQA.Selenium.Cookie newCookie4 = new OpenQA.Selenium.Cookie("SID", "", "", DateTime.Now.AddDays(1));
            OpenQA.Selenium.Cookie newCookie5 = new OpenQA.Selenium.Cookie("lang", "", "", DateTime.Now.AddDays(1));

            listcookie.AddCookie(newCookie0);
            listcookie.AddCookie(newCookie1);
            listcookie.AddCookie(newCookie2);
            listcookie.AddCookie(newCookie3);
            listcookie.AddCookie(newCookie4);
            listcookie.AddCookie(newCookie5);
            #endregion

            //關閉拓元的提示
            driver.FindElement(By.ClassName("closeNotice")).Click();

            driver.Navigate().Refresh();

            //滾動捲軸
            IJavaScriptExecutor js = (IJavaScriptExecutor)driver;
            js.ExecuteScript("window.scrollTo(0, document.body.scrollHeight/5);");

            //點選立即購票
            ClickBuyTicketNow();

            //取得購票連結
            try
            {
                GoAreaUrl  = driver.FindElement(By.XPath("//*[@id='gameList']/table/tbody/tr/td[4]/input")).GetAttribute("data-href");
                driver.Url = "https://tixcraft.com" + GoAreaUrl;
            }
            catch (Exception ex)
            {
                Console.WriteLine("取得購票連結錯誤,重新取得中...");
                ErrorCheck = true;

                while (ErrorCheck)
                {
                    try
                    {
                        GoAreaUrl  = driver.FindElement(By.XPath("//*[@id='gameList']/table/tbody/tr/td[4]/input")).GetAttribute("data-href");
                        driver.Url = "https://tixcraft.com" + GoAreaUrl;
                        ErrorCheck = false;
                        break;
                    }
                    catch
                    {
                        Console.WriteLine("取得購票連結錯誤,重新取得中...");
                        driver.Navigate().Refresh();
                        ClickBuyTicketNow();
                    }
                }
            }


            //座位關鍵字點擊
            try
            {
                driver.FindElement(By.XPath("//a[contains(text(), '" + KeyWord + "')]")).Click();
            }
            catch (Exception ex)
            {
                Console.WriteLine("查詢座位關鍵字錯誤,重新取得中...");
                AreaKeywordLoss = true;

                if (AreaKeywordLoss)
                {
                    for (int i = 0; i < 4; i++)
                    {
                        if (i == 0)
                        {
                            js.ExecuteScript("window.scrollTo(0, document.body.scrollHeight/4);");
                        }
                        else if (i == 1)
                        {
                            js.ExecuteScript("window.scrollTo(0, document.body.scrollHeight/2);");
                        }
                        else if (i == 2)
                        {
                            js.ExecuteScript("window.scrollTo(0, document.body.scrollHeight/4*3);");
                        }
                        else
                        {
                            js.ExecuteScript("window.scrollTo(0, document.body.scrollHeight);");
                        }

                        //關鍵字點擊
                        try
                        {
                            driver.FindElement(By.XPath("//*[contains(text(), '" + KeyWord + "')]")).Click();
                            AreaKeywordLoss = false;
                            break;
                        }
                        catch
                        {
                            Console.WriteLine("第" + (i + 1) + "次找不到關鍵字座位");
                            if (i == 4)
                            {
                                Console.WriteLine("找不到關鍵字座位,請重新設定關鍵字座位");
                            }
                        }
                    }
                }
            }

            //選擇張數
            DropDownList_SelectValue(By.ClassName("mobile-select"), TicketPiece.ToString());

            //同意會員服務條款
            driver.FindElement(By.XPath("//*[@id='TicketForm_agree']")).Click();

            //等待購買方式出現後繼續,只等300秒,不然會拋出錯誤訊息。等候結帳應該不會等太久
            new WebDriverWait(driver, TimeSpan.FromSeconds(300)).Until(ExpectedConditions.ElementExists((By.Id("PaymentForm_payment_id_36"))));

            //選擇信用卡結帳
            driver.FindElement(By.XPath("//*[@id='PaymentForm_payment_id_36']")).Click();

            //選擇iBon結帳



            ////利用HtmlAgilityPack解網頁程式碼
            //HtmlWeb web = new HtmlWeb();
            //var HtmlDoc = web.Load("https://tixcraft.com" + GoAreaUrl);
            //var AllAreaUl = HtmlDoc.DocumentNode.SelectSingleNode("//div[@class='zone area-list']").SelectNodes(".//ul");
        }