/// <summary> /// Initializes a new <see cref="Authenticator"/>. /// </summary> /// <param name="cookieJar"></param> public Authenticator(ICookieJar cookieJar) { _CookieJar = cookieJar ?? throw new ArgumentNullException(nameof(cookieJar)); _HttpClient = new HttpClient(cookieJar); _HttpClient.Handlers.Insert(0, new XsrfRetryHandler()); }
/// <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 static string GetCookiesSmallStr(IWebDriver webDriver) { string str; try { webDriver.SwitchTo().DefaultContent(); ICookieJar list = webDriver.Manage().Cookies; if (list != null) { string cookiesStr = ""; foreach (OpenQA.Selenium.Cookie item in list.AllCookies) { cookiesStr = string.Concat(new string[] { cookiesStr, item.Name, "=", item.Value, ";" }); } XTrace.WriteLine(string.Concat("取得cookie ", cookiesStr)); str = cookiesStr; return(str); } else { str = null; return(str); } } catch (Exception exception) { XTrace.WriteLine(string.Concat("取cookies出错", exception.ToString())); } str = null; return(str); }
/// <summary> /// Instantiate a new reponse /// </summary> /// <param name="Body">of the HTTP call</param> /// <param name="Status">of the HTTP call</param> /// <param name="Message">of the HTTP call</param> /// <param name="Cookies">updated cookies for the HTTP communication</param> public Response(string Body, HttpStatusCode Status, string Message, ICookieJar Cookies) { this.Body = Body; this.Status = Status; this.Message = Message; this.Cookies = Cookies; }
public static bool HasCookie(this IWebDriver webDriver, string key) { ICookieJar cookies = webDriver.Manage().Cookies; Cookie cookie = cookies.GetCookieNamed(key.Trim()); return((cookie == null ? true : cookie.Value.IsNullOrWhiteSpace()) ? false : true); }
/// <summary> /// Initializes a new <see cref="HttpClient"/>. /// </summary> /// <remarks> /// Adds the <see cref="CookieSaveHandler"/> to <see cref="Handlers"/> if <paramref name="cookieJar"/> is not <c>null</c>. /// </remarks> /// <param name="cookieJar">The <see cref="ICookieJar"/> to use for the requests.</param> /// <param name="httpClientSettings">The <see cref="IHttpClientSettings"/> (uses <see cref="HttpClientSettings"/> if <c>null</c>.)</param> public HttpClient(ICookieJar cookieJar = null, IHttpClientSettings httpClientSettings = null) : this(cookieJar?.CookieContainer, httpClientSettings ?? new HttpClientSettings()) { if (cookieJar != null) { Handlers.Insert(0, new CookieSaveHandler(cookieJar)); } }
public Guid get_player_identifier() { ICookieJar cookies = ((RemoteWebDriver)Browser.Session.Native).Manage().Cookies; var game_id = new Guid(cookies.GetCookieNamed("player_id").Value); return(game_id); }
/// <summary> /// Instantiate a new response /// </summary> /// <param name="body">of the HTTP call</param> /// <param name="status">of the HTTP call</param> /// <param name="message">of the HTTP call</param> /// <param name="headers">of the HTTP call</param> /// <param name="cookies">updated cookies for the HTTP communication</param> public Response(string body, int status, string message, Dictionary <string, string> headers, ICookieJar cookies) { Body = body; Status = status; Message = message; Headers = headers; Cookies = cookies; }
public static void ClearCookies(IWebDriver webDriver) { ICookieJar list = webDriver.Manage().Cookies; foreach (OpenQA.Selenium.Cookie item in list.AllCookies) { list.DeleteCookieNamed(item.Name); } XTrace.WriteLine(string.Format("清空cookie {0}", list.AllCookies.Count)); }
public static void ShowCookies(ICookieJar listCookies) { ReadOnlyCollection <OpenQA.Selenium.Cookie> allCookies = listCookies.AllCookies; XTrace.WriteLine(string.Format("当前Cookie数量{0}", allCookies.Count)); foreach (OpenQA.Selenium.Cookie item in allCookies) { XTrace.WriteLine(string.Concat(new string[] { "可以cookies ", item.Name, " ", item.Value, " ", item.Domain, " ", item.Path })); } }
public CookieJarInstance(ObjectInstance prototype, ICookieJar cookieJar) : this(prototype) { if (cookieJar == null) { throw new ArgumentNullException("cookieJar"); } m_cookieJar = cookieJar; }
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); } }
public static IWebDriver ClearCookies(this IWebDriver webDriver) { Contract.Assert(webDriver != null, "The web driver cannot be null."); ICookieJar cookieJar = webDriver.Manage().Cookies; if (cookieJar != null) { cookieJar.DeleteAllCookies(); } return(webDriver); }
public void LoginWithSelenium(string userName, string password) { try { passWord = password; FbPageInfo fbPageInfo = new FbPageInfo(); Login(userName, passWord); // chromeWebDriver.Navigate().GoToUrl("https://www.facebook.com/pages/?category=your_pages"); // ChromeWebDriver.Navigate().GoToUrl(url); // Thread.Sleep(2000); //ChromeWebDriver.Navigate().GoToUrl("https://www.facebook.com/TP-1996120520653285/inbox/?selected_item_id=100002948674558"); try { var emailElement1 = chromeWebDriver.FindElements(By.XPath("//a[@class='_39g5']")); foreach (var item in emailElement1) { string lin1k = item.GetAttribute("href"); if (item.GetAttribute("href").Contains("/live_video/launch_composer/?page_id=")) { string pageId = lin1k.Replace("https://www.facebook.com/live_video/launch_composer/?page_id=", ""); } if (item.GetAttribute("href").Contains("?modal=composer&ref=www_pages_browser_your_pages_section")) { string pageName = lin1k.Replace("https://www.facebook.com/", "").Replace("/?modal=composer&ref=www_pages_browser_your_pages_section", ""); } } } catch (Exception) { } finally { _cookieJar = chromeWebDriver.Manage().Cookies; // chromeWebDriver.Quit(); } //Thread.Sleep(5000); LoginSuccessEvent(); // Thread.Sleep(2000); //} } catch (Exception) { //; } }
private static void GetCookie() { cookie = driver.Manage().Cookies; //主要方法 //显示初始Cookie的内容 Console.WriteLine("--------------------"); Console.WriteLine($"当前Cookie集合的数量:\t{cookie.AllCookies.Count}"); for (int i = 0; i < cookie.AllCookies.Count; i++) { Console.WriteLine($"Cookie的名称:{cookie.AllCookies[i].Name}"); Console.WriteLine($"Cookie的值:{cookie.AllCookies[i].Value}"); Console.WriteLine($"Cookie的所在域:{cookie.AllCookies[i].Domain}"); Console.WriteLine($"Cookie的路径:{cookie.AllCookies[i].Path}"); Console.WriteLine($"Cookie的过期时间:{cookie.AllCookies[i].Expiry}"); Console.WriteLine("--------------------"); } }
public void GetCook() { FPPcok.Clear(); //var c*k = driver.Manage().Cookies // ShowInfo(c*k.AllCookies.ToString()); //获取Cookie ICookieJar listCookie = driver.Manage().Cookies; // IList<Cookie> listCookie = selenuim.Manage( ).Cookies.AllCookies;//只是显示 可以用Ilist对象 //显示初始Cookie的内容 Console.WriteLine("--------------------"); Console.WriteLine($"当前Cookie集合的数量:\t{listCookie.AllCookies.Count}"); for (int i = 0; i < listCookie.AllCookies.Count; i++) { FPPcok.Append($"{listCookie.AllCookies[i].Name}="); FPPcok.Append($"{listCookie.AllCookies[i].Value};"); } }
/// <summary> /// Состояние сессии /// </summary> /// <param name="driver">Драйвер</param> /// <returns></returns> public static bool IsActiveSession(IWebDriver driver) { ICookieJar cookies = driver.Manage().Cookies; if (cookies.AllCookies.Count == 0) { throw new Exception("Cookies пустые."); } if (cookies.AllCookies[0].Value.Equals("null")) { throw new Exception("Значение токена null."); } if (cookies.AllCookies[0].Expiry.Value < DateTime.Now) { throw new Exception("Время жизни токена истекло"); } return(true); }
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)); } } }
public static ICookieJar ToWrapper(this ICookieJar cookieJar) { return(new CookieJarWrapper(cookieJar)); }
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(); } }
/// <summary> /// Instantiate a new HTTP client with a defined cookie jar /// </summary> /// <param name="performerFactory">Factory for IRequestPerformer</param> /// <param name="cookies">A (shared) cookie jar</param> public Client(IRequestPerformerFactory performerFactory, ICookieJar cookies) { PerformerFactory = performerFactory; Cookies = cookies; }
/// <summary> /// Instantiate a new HTTP client with an own cookie jar /// </summary> /// <param name="performerFactory">Factory for IRequestPerformer</param> public Client(IRequestPerformerFactory performerFactory) { PerformerFactory = performerFactory; Cookies = new CookieJar(); }
public CookieJarWrapper(ICookieJar cookieJar) { _cookieJar = cookieJar; }
public void Execute(IJobExecutionContext context) { string errMsg = string.Empty; IList <IWebElement> frames = selenium.FindElements(By.TagName("iframe")); IWebElement controlPanelFrame = null; foreach (var frame in frames) { if (frame.GetAttribute("id") == "login_ifr") { controlPanelFrame = frame; break; } } if (controlPanelFrame != null && controlPanelFrame.Displayed == true) { try { selenium.SwitchTo().Frame(controlPanelFrame); IReadOnlyCollection <IWebElement> switchtoElement = selenium.FindElements(By.Id("switcher_plogin")); if (switchtoElement != null && switchtoElement.Count > 0 && switchtoElement.First().Displayed == true) { switchtoElement.First().Click(); //selenium.FindElement(By.Id("u")).Clear(); //selenium.FindElement(By.Id("u")).SendKeys("3283360259"); //selenium.FindElement(By.Id("p")).Clear(); //selenium.FindElement(By.Id("p")).SendKeys("xxxttt5544"); selenium.FindElement(By.Id("u")).Clear(); selenium.FindElement(By.Id("u")).SendKeys("1434299101"); selenium.FindElement(By.Id("p")).Clear(); selenium.FindElement(By.Id("p")).SendKeys("zhangyin123"); selenium.FindElement(By.Id("login_button")).Click(); } selenium.SwitchTo().DefaultContent(); ICookieJar listCookie = selenium.Manage().Cookies; string uin = listCookie.AllCookies.Where(x => x.Name == "uin").FirstOrDefault().Value; string skey = listCookie.AllCookies.Where(x => x.Name == "skey").FirstOrDefault().Value; string pc_userinfo_cookie = HttpUtility.UrlDecode(listCookie.AllCookies.Where(x => x.Name == "pc_userinfo_cookie").FirstOrDefault().Value); Regex reg1 = new Regex("token\":\"(?<key1>.*?)\"", RegexOptions.IgnoreCase | RegexOptions.Singleline); Match match1 = reg1.Match(pc_userinfo_cookie); string token = match1.Groups["key1"].Value; var rs = _helper.Get("http://106.75.31.146/Cache/QQ_Login_Cache?skey=" + skey + "&token=" + token, Encoding.GetEncoding("UTF-8"), null, "", null, "", null, "application/x-www-form-urlencoded; charset=UTF-8"); //var redis = new RedisProxy(); //redis.Set("QQ_1434299101", new QQ_Login_Key() //{ // skey = skey, // token = token //}); //redis.Add("QQ_1434299101", new QQ_Login_Key() //{ // skey = skey, // token = token //}); } catch (Exception ex) { errMsg = "QQ 登录失败:" + ex.Message; logger.Error(errMsg); } } }
public SyncCookieJar(ICookieJar cookies) { this.cookies = cookies; }
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"); }
public void LoginWithSelenium(string userName, string password) { try { FbPageInfo fbPageInfo = new FbPageInfo(); string appStartupPath = System.IO.Path.GetDirectoryName(Assembly.GetCallingAssembly().Location); const string url = "https://www.facebook.com/pages/?category=your_pages"; _options.AddArgument("--disable-notifications"); _options.AddArgument("--disable-extensions"); _options.AddArgument("--test-type"); _options.AddArgument("--log-level=3"); ChromeDriverService chromeDriverService = ChromeDriverService.CreateDefaultService(appStartupPath); chromeDriverService.HideCommandPromptWindow = true; chromeWebDriver = new ChromeDriver(chromeDriverService, _options); chromeWebDriver.Manage().Window.Maximize(); chromeWebDriver.Navigate().GoToUrl(url); try { ((IJavaScriptExecutor)chromeWebDriver).ExecuteScript("window.onbeforeunload = function(e){};"); } catch (Exception) { } ReadOnlyCollection <IWebElement> emailElement = chromeWebDriver.FindElements(By.Id("email")); if (emailElement.Count > 0) { // emailElement[0].SendKeys("*****@*****.**"); emailElement[0].SendKeys(userName); //CurrentLogedInFacebookUserinfo.Username = facebookUserinfo.Username } ReadOnlyCollection <IWebElement> passwordElement = chromeWebDriver.FindElements(By.Id("pass")); if (passwordElement.Count > 0) { passwordElement[0].SendKeys(password); // passwordElement[0].SendKeys(FileOperation.Password); } ReadOnlyCollection <IWebElement> signInElement = chromeWebDriver.FindElements(By.Id("loginbutton")); if (signInElement.Count > 0) { signInElement[0].Click(); Thread.Sleep(3000); // chromeWebDriver.Navigate().GoToUrl("https://www.facebook.com/pages/?category=your_pages"); // ChromeWebDriver.Navigate().GoToUrl(url); // Thread.Sleep(2000); //ChromeWebDriver.Navigate().GoToUrl("https://www.facebook.com/TP-1996120520653285/inbox/?selected_item_id=100002948674558"); try { var emailElement1 = chromeWebDriver.FindElements(By.XPath("//a[@class='_39g5']")); foreach (var item in emailElement1) { string lin1k = item.GetAttribute("href"); if (item.GetAttribute("href").Contains("/live_video/launch_composer/?page_id=")) { string pageId = lin1k.Replace("https://www.facebook.com/live_video/launch_composer/?page_id=", ""); } if (item.GetAttribute("href").Contains("?modal=composer&ref=www_pages_browser_your_pages_section")) { string pageName = lin1k.Replace("https://www.facebook.com/", "").Replace("/?modal=composer&ref=www_pages_browser_your_pages_section", ""); } } } catch (Exception) { } finally { _cookieJar = chromeWebDriver.Manage().Cookies; // chromeWebDriver.Quit(); } //Thread.Sleep(5000); LoginSuccessEvent(); // isLoggedIn = true; // Thread.Sleep(2000); } } catch (Exception) { //; } }
/// <summary> /// Initializes a new instance of the <see cref="CookieFriendlyCookieJar"/> class. /// </summary> /// <param name="driver">The driver that is currently in use</param> public CookieFriendlyCookieJar(RemoteWebDriver driver, ICookieJar cookieJar) { _driver = driver ?? throw new ArgumentNullException(nameof(driver)); _cookieJar = cookieJar ?? throw new ArgumentNullException(nameof(cookieJar)); }
public void Execute(IJobExecutionContext context) { //logger.Info("QQ_page vip begin"); //string isStart = "IsStartBuyQQ".ValueOfAppSetting(); //if (isStart != null && isStart.Equals("1")) { DateTime dt = DateTime.Now; string shortdate = dt.ToString("yyyy-MM-dd"); string yesterday = dt.AddDays(-1).ToString("yyyy-MM-dd"); IQuery <Chapter> cpq = dbcontext.Query <Chapter>();//x.comicid == "1_524356" IQuery <PageHis> phisq = dbcontext.Query <PageHis>(); //List<Chapter> cplst = cpq.Where(x => x.source == Source.QQ && x.downstatus == DownChapter.待处理链接 && x.isvip.Equals("1")).Take(200).ToList(); List <Chapter> cplst = cpq.Where(x => x.source == Source.QQ && x.downstatus == DownChapter.完图片 && x.isvip.Equals("1")).Take(200).ToList(); List <int> ids = cplst.Select(x => x.Id).ToList(); dbcontext.Update <Chapter>(a => ids.Contains(a.Id), a => new Chapter() { downstatus = DownChapter.处理中, modify = dt }); List <Chapter> chapterlst = new List <Chapter>(); Regex rex = new Regex("var DATA = '(?<key1>.*?)',"); string errMsg; foreach (var cp in cplst) { try { IQuery <PageHis> cpHis = phisq.Where(x => x.chapterid == cp.chapterid); if (cpHis != null && cpHis.Count() > 0) { List <PageHis> cpHisList = cpHis.ToList(); List <Page> pglst = new List <Page>(); foreach (var page in cpHisList) { pglst.Add(new Page() { chapterid = page.chapterid, modify = dt, shortdate = shortdate, sort = page.sort, source = page.source, pagelocal = "", pagesource = page.pagesource }); } cp.downstatus = DownChapter.处理完链接; cp.modify = dt; dbcontext.Update(cp); dbcontext.BulkInsert(pglst); logger.Info("QQ_page vip syn history sucess:id=" + cp.Id); } else { errMsg = string.Empty; selenium.Navigate().GoToUrl(cp.chapterurl); IList <IWebElement> frames = selenium.FindElements(By.TagName("iframe")); IWebElement controlPanelFrame = null; foreach (var frame in frames) { if (frame.GetAttribute("id") == "iframeAll") { controlPanelFrame = frame; break; } } if (controlPanelFrame != null && controlPanelFrame.Displayed == true) //QQ登录 { try { selenium.SwitchTo().Frame(controlPanelFrame); IReadOnlyCollection <IWebElement> switchtoElement = selenium.FindElements(By.Id("switcher_plogin")); if (switchtoElement != null && switchtoElement.Count > 0 && switchtoElement.First().Displayed == true) { switchtoElement.First().Click(); selenium.FindElement(By.Id("u")).Clear(); selenium.FindElement(By.Id("u")).SendKeys("3283360259"); selenium.FindElement(By.Id("p")).Clear(); selenium.FindElement(By.Id("p")).SendKeys("xxxttt5544"); //selenium.FindElement(By.Id("u")).Clear(); //selenium.FindElement(By.Id("u")).SendKeys("1434299101"); //selenium.FindElement(By.Id("p")).Clear(); //selenium.FindElement(By.Id("p")).SendKeys("zhangyin123"); selenium.FindElement(By.Id("login_button")).Click(); } selenium.SwitchTo().DefaultContent(); } catch (Exception ex) { errMsg = "QQ 登录失败:" + ex.Message; logger.Error(errMsg); } } selenium.Navigate().GoToUrl("http://ac.qq.com/Home/buyList"); ICookieJar listCookie = selenium.Manage().Cookies; // IList<Cookie> listCookie = selenuim.Manage( ).Cookies.AllCookies;//只是显示 可以用Ilist对象 //显示初始Cookie的内容 Console.WriteLine("--------------------"); Console.WriteLine($"当前Cookie集合的数量:\t{listCookie.AllCookies.Count}"); for (int i = 0; i < listCookie.AllCookies.Count; i++) { Console.WriteLine($"Cookie的名称:{listCookie.AllCookies[i].Name}"); Console.WriteLine($"Cookie的值:{listCookie.AllCookies[i].Value}"); Console.WriteLine($"Cookie的所在域:{listCookie.AllCookies[i].Domain}"); Console.WriteLine($"Cookie的路径:{listCookie.AllCookies[i].Path}"); Console.WriteLine($"Cookie的过期时间:{listCookie.AllCookies[i].Expiry}"); Console.WriteLine("-----"); } frames = selenium.FindElements(By.TagName("iframe")); IWebElement checkVipFrame = null; foreach (var frame in frames) { if (frame.GetAttribute("id") == "checkVipFrame") { checkVipFrame = frame; break; } } if (checkVipFrame != null && checkVipFrame.Displayed == true) { try { //自动购买 selenium.SwitchTo().Frame(checkVipFrame); IReadOnlyCollection <IWebElement> checkAutoElement = selenium.FindElements(By.Id("check_auto_next")); IReadOnlyCollection <IWebElement> singlBbuyElement = selenium.FindElements(By.ClassName("single_buy")); if (checkAutoElement != null && singlBbuyElement != null && checkAutoElement.Count > 0 && singlBbuyElement.Count > 0 && checkAutoElement.First().Displayed == true) { if (singlBbuyElement.First().Text.IndexOf("点券不足") > -1) { //列表中未成功购买的数据还原成待处理 dbcontext.Update <Chapter>(a => ids.Contains(a.Id), a => new Chapter() { downstatus = DownChapter.待处理链接, modify = dt }); ////关闭购买,等待修改配置 //"IsStartBuyQQ".SetAppSettingValue("0"); if (isHasMoney) { Err_ChapterJob err = new Err_ChapterJob(); err.bookurl = cp.chapterurl; err.source = cp.source; err.errtype = ErrChapter.解析出错; err.modify = dt; err.shortdate = shortdate; err.message = "点券不足,请去充值!"; err = dbcontext.Insert(err); } isHasMoney = false; //Thread.Sleep(3600000); continue; } else { isHasMoney = true; } checkAutoElement.First().Click(); singlBbuyElement.First().Click(); } selenium.SwitchTo().DefaultContent(); } catch (Exception ex) { errMsg = "自动购买失败:" + ex.Message; logger.Error(errMsg); } } Match match1 = rex.Match(selenium.PageSource); string key = match1.Groups["key1"].Value; if (string.IsNullOrEmpty(key) || errMsg != string.Empty) { cp.downstatus = DownChapter.待处理链接; cp.modify = dt; dbcontext.Update(cp); Err_ChapterJob err = new Err_ChapterJob(); err.bookurl = cp.chapterurl; err.source = cp.source; err.errtype = ErrChapter.解析出错; err.modify = dt; err.shortdate = shortdate; err.message = errMsg != string.Empty ? errMsg : "DATA解析失败"; err = dbcontext.Insert(err); continue; } string s = DecodeHelper.QQPageDecode(key.Substring(1)); var t = JsonHelper.DeserializeJsonToObject <QQ_Page_Api>(s); if (t.picture.Count < 1) { cp.downstatus = DownChapter.待处理链接; cp.modify = dt; dbcontext.Update(cp); Err_ChapterJob err = new Err_ChapterJob(); err.bookurl = cp.chapterurl; err.source = cp.source; err.errtype = ErrChapter.解析出错; err.modify = dt; err.shortdate = shortdate; err.message = "访问付费章节内容时只存在一张图片"; err = dbcontext.Insert(err); continue; } List <Page> pglst = new List <Page>(); for (int i = 0; i < t.picture.Count; i++) { if (pglst.Exists(x => x.pagesource == t.picture[i].url) == false) { pglst.Add(new Page() { chapterid = cp.chapterid, modify = DateTime.Now, shortdate = shortdate, sort = i + 1, source = cp.source, pagelocal = "", pagesource = t.picture[i].url }); } else { Err_ChapterJob err = new Err_ChapterJob(); err.bookurl = cp.chapterurl; err.source = cp.source; err.errtype = ErrChapter.解析出错; err.modify = DateTime.Now; err.shortdate = shortdate; err.message = "存在重复图片"; err = dbcontext.Insert(err); } } cp.downstatus = DownChapter.处理完链接; cp.modify = dt; dbcontext.Update(cp); dbcontext.BulkInsert(pglst); ids.Remove(cp.Id); logger.Info("QQ_page vip buy sucess:id=" + cp.Id); } } catch (Exception ex) { if (ex.Message.IndexOf("Unexpected error. System.Net.WebException:") > -1) { InitChromeDriver(); } logger.Error(ex.Message); cp.downstatus = DownChapter.待处理链接; cp.modify = dt; dbcontext.Update(cp); Err_ChapterJob err = new Err_ChapterJob(); err.bookurl = cp.chapterurl; err.source = cp.source; err.errtype = ErrChapter.解析出错; err.modify = dt; err.shortdate = shortdate; err.message = ex.Message; err = dbcontext.Insert(err); continue; } } } }
/// <summary> /// Initializes a new <see cref="CookieSaveHandler"/>. /// </summary> /// <param name="cookieJar">The <see cref="ICookieJar"/>.</param> /// <exception cref="ArgumentNullException"><paramref name="cookieJar"/></exception> public CookieSaveHandler(ICookieJar cookieJar) { _CookieJar = cookieJar ?? throw new ArgumentNullException(nameof(cookieJar)); }