protected void Type(string path, string pathType, string value) { if (pathType == "id") { IWebElement element = driver.FindElementById(path); element.SendKeys(value); TestCase.Log("Entered " + value + " at element with id=" + path); } if (pathType == "name") { IWebElement element = driver.FindElementByName(path); element.SendKeys(value); TestCase.Log("Entered " + value + " at element with name=" + path); } if (pathType == "class") { IWebElement element = driver.FindElementByClassName(path); element.SendKeys(value); TestCase.Log("Entered " + value + " at element with class=" + path); } if (pathType == "xpath") { IWebElement element = driver.FindElementByXPath(path); element.SendKeys(value); TestCase.Log("Entered " + value + " at element with xpath=" + path); } }
private void LoginButton_Click(object sender, RoutedEventArgs e) { if (User.Text == "" || Password.Password == "") { MessageBox.Show("Insert user and password"); return; } PhantomJSDriverService srv = PhantomJSDriverService.CreateDefaultService(); srv.SuppressInitialDiagnosticInformation = true; srv.HideCommandPromptWindow = true; using (PhantomJSDriver chrDriver = new PhantomJSDriver(srv)) { try { chrDriver.Manage().Window.Minimize(); } catch (Exception ex) { //Evbb } chrDriver.Url = "https://idp.polito.it/idp/x509mixed-login"; chrDriver.Navigate(); IWebElement element = chrDriver.FindElementById("j_username"); element.SendKeys(User.Text); element = chrDriver.FindElementById("j_password"); element.SendKeys(Password.Password); element = chrDriver.FindElementsByTagName("button").Where((x) => { try { x.FindElement(By.Id("usernamepassword")); return(true); } catch (Exception ex) { return(false); } }).First(); element.Click(); chrDriver.Url = "https://didattica.polito.it/portal/page/portal/home/Studente"; chrDriver.Navigate(); if (chrDriver.Manage().Cookies.GetCookieNamed("ShibCookie") != null) { chrDriver.Manage().Cookies.AllCookies.ToList() .ForEach(x => jar.Add(new System.Net.Cookie(x.Name, x.Value, x.Path, x.Domain))); this.DialogResult = true; } else { jar = null; this.DialogResult = false; } this.Close(); } }
public AccountDetail GetAccountDetails() { if (driver != null) { string abc = string.Empty; Document body = null; ReadOnlyCollection <IWebElement> alltables; try { driver.SwitchTo().Window(driver.CurrentWindowHandle); driver.SwitchTo().Frame("frame_menu"); driver.FindElementById("RRADTlink").Click(); driver.SwitchTo().Window(driver.CurrentWindowHandle); driver.SwitchTo().Frame("frame_txn"); SelectElement elem = new SelectElement(driver.FindElementById("fldacctnodesc")); elem.SelectByValue(this.Value); driver.FindElementByName("fldsubmit").Click(); alltables = driver.FindElementsByClassName("infotable"); abc = alltables[0].GetAttribute("innerHTML"); body = Supremes.Dcsoup.Parse(abc); } catch { throw new Exception("(ErrorCode:6) Service Or Network not Available Or Might be Some Rendering Problem Try again."); } AccountDetail detail = new AccountDetail(this.Value, driver); detail.AccountTitle = body.Body.TextNodes[1].Text; detail.AccountNumber = body.Body.TextNodes[4].Text; abc = alltables[2].GetAttribute("innerHTML"); body = Supremes.Dcsoup.Parse(abc); detail.CurrentBalance = Convert.ToDouble(body.Body.TextNodes[2].Text.Replace(",", "")); detail.AmountOnHold = Convert.ToDouble(body.Body.TextNodes[4].Text.Replace(",", "")); detail.UnClearedFunds = Convert.ToDouble(body.Body.TextNodes[6].Text.Replace(",", "")); detail.OverDraftLimit = Convert.ToDouble(body.Body.TextNodes[8].Text.Replace(",", "")); detail.AvailableBalance = Convert.ToDouble(body.Body.TextNodes[10].Text.Replace(",", "")); detail.NetAvailableBalanceForWithDrawls = Convert.ToDouble(body.Body.TextNodes[12].Text.Replace(",", "")); return(detail); } else { throw new Exception("(ErrorCode:5) Account object not initialized"); } }
private void GetChapterComicPage() { var service = PhantomJSDriverService.CreateDefaultService(); service.DiskCache = true; service.IgnoreSslErrors = true; service.HideCommandPromptWindow = true; service.LoadImages = false; service.ProxyType = "none"; service.LocalToRemoteUrlAccess = true; PhantomJSDriver driver = new PhantomJSDriver(service, new PhantomJSOptions(), TimeSpan.FromSeconds(120)); driver.Navigate().GoToUrl(Url); var element = driver.FindElementById("page_select"); foreach (var pages in driver.FindElements(By.XPath("//*[@id=\"page_select\"]/option"))) { var page = new ComicPage(); page.PageImgUrl = "https:" + pages.GetAttribute("value"); page.PageNo = pages.Text.GetNumber(); _comicPageList.Add(page); } driver.Close(); driver.Dispose(); }
static void Main(string[] args) { using (var driver = new PhantomJSDriver()) { driver.Navigate().GoToUrl("http://www.google.com/"); var query = driver.FindElementByName("q"); query.SendKeys("hello"); query.Submit(); var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10)); wait.Until(d => d.Title.ToLower().StartsWith("hello")); Console.WriteLine("Page title: " + driver.Title); var resultsPanel = driver.FindElementById("search"); var searchResults = resultsPanel.FindElements(By.XPath(".//a")); foreach (var result in searchResults) { Console.WriteLine(result.Text); } } Console.ReadKey(); }
private void login() { try { var username = driver.FindElementById("login-username"); var password = driver.FindElementById("login-password"); username.SendKeys("oddsbetting"); password.SendKeys("oddsbettings"); var button = driver.FindElementByName("login-submit"); button.Click(); } catch (Exception e) { return; } }
public override bool Execute(PhantomJSDriver driver) { IWebElement element = null; try { switch (Parameters[0]) { case "id": element = driver.FindElementById(Parameters[1]); break; case "name": element = driver.FindElementByName(Parameters[1]); break; case "class": element = driver.FindElementByClassName(Parameters[1]); break; case "text": element = driver.FindElementByLinkText(Parameters[1]); break; } } catch (Exception e) { //Element was not found return(false); } //Wrong parameters were used return(element != null); }
private void SubmitBtn_Click(object sender, EventArgs e) { if (MainGrpBox.Controls.OfType <CheckBox>().Where(x => x.Checked).Count() != 2) { MessageBox.Show("Select 2 values please.", "Otaku Time"); return; } string values = String.Join(",", MainGrpBox.Controls.OfType <CheckBox>().Where(x => x.Checked).Select(x => x.Tag)); _Driver.ExecuteScript($"document.getElementById('answerCap').setAttribute('value','{values}')"); _Driver.FindElementById("formVerify").Submit(); if (_Driver.Title == "http://kissanime.ru/Special/AreYouHuman2") //user is wrong. So much for user interaction. { //restart the process. foreach (CheckBox Chk in MainGrpBox.Controls.Cast <CheckBox>()) { Chk.Checked = false; } _Driver.Navigate().GoToUrl(_Url); RenderScreen(); } else { DialogResult = DialogResult.OK; Close(); } }
public bool Login(string username, string password) { bool flag = false; try { driver.Navigate().GoToUrl(SignInUrl); Thread.Sleep(1000); takescreenshot("login screen"); //the driver can now provide you with what you need (it will execute the script) //get the source of the page //fully navigate the dom ShowDriverState(); var pathElement = driver.FindElementById("UserName"); pathElement.SendKeys(username); Thread.Sleep(500); var pass = driver.FindElementById("Password"); pass.SendKeys(password); var signin = driver.FindElementByClassName("tyler-btn-primary"); Thread.Sleep(500); signin.Submit(); var body = new WebDriverWait(driver, TimeSpan.FromSeconds(submit_wait)).Until(ExpectedConditions.UrlContains("Portal")); Thread.Sleep(500); if (driver.Url != HomePageUrl) { Console.WriteLine(driver.Title); Console.WriteLine(driver.Url); flag = false; } else { Console.WriteLine(driver.Title); Console.WriteLine(driver.Url); flag = true; } } catch (Exception ex) { takescreenshot("exception login"); Console.WriteLine(driver.Url); Console.WriteLine(ex.Message); flag = false; } takescreenshot("afterLoginScreen"); return(flag); }
/// <summary> /// Use to Check Browser footprint /// </summary> /// <param name="driver"></param> /// <param name="wait"></param> public void TestUnique(PhantomJSDriver driver, WebDriverWait wait) { driver.Navigate().GoToUrl("https://amiunique.org/"); var button = driver.FindElementById("link"); button.Click(); wait.Until((d) => { return(ExpectedConditions.ElementExists(By.Id("content"))); }); Thread.Sleep(TimeSpan.FromSeconds(60)); driver.FindElementById("detBut").Click(); }
public bool Login() { PhantomJsDriver.Navigate().GoToUrl($"{BaseUrl}{LoginUrl}"); PhantomJsDriver.FindElementById("ctl00_MainContent_InputLogin").SendKeys(_username); PhantomJsDriver.FindElementById("ctl00_MainContent_InputPassword").SendKeys(_password); PhantomJsDriver.FindElementById("ctl00_MainContent_btnLogin").Click(); PhantomJsDriver.WaitForAjax(); return(PhantomJsDriver.Url != $"{BaseUrl}{LoginUrl}"); }
private async Task <string> GetGoogleLink(string attributeNumber) { _tryCount++; if (_clicked == false) { _phantomObject.Navigate().Refresh(); var runTheScript = _phantomObject.FindElementsByClassName("episode").First(x => x.GetAttribute("data-value") == attributeNumber); runTheScript.Click(); _clicked = true; } var firstpreval = _phantomObject.FindElementsByTagName("a"); var secondspreval = firstpreval.Where(x => x.Text != "").Select(x => x).ToList(); var val = secondspreval.FirstOrDefault(x => x.Text.Contains("mp4")); var alternativeSourceUrl = ""; try { alternativeSourceUrl = _phantomObject.FindElementById("mVideo").GetAttribute("src"); } catch (Exception) { } if (!string.IsNullOrWhiteSpace(alternativeSourceUrl)) { string value; if (alternativeSourceUrl.Contains("openload")) { value = StaticsClass.GetOpenloadLink(alternativeSourceUrl); } else if (alternativeSourceUrl.Contains("rapidvideo")) { value = await WebDriverClass.GetRapidVideoLink(alternativeSourceUrl); } else { value = alternativeSourceUrl; // its the google link. weird. } _phantomObject.Navigate().GoToUrl(AnimeUrl); _clicked = false; return(value); } if (val == null) { if (_tryCount <= 5) { await Task.Delay(300); return((await GetGoogleLink(attributeNumber)).Replace("&", "&"));; } MessageBox.Show("Video is unavailable, please try again later.", "Otaku Time", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); _tryCount = 0; return("no"); } _tryCount = 0; var retval = val.GetAttribute("href"); _clicked = false; return(retval); }
public ActionResult Translate(string text) { PhantomJSDriver driver = new PhantomJSDriver(); driver.Navigate().GoToUrl("https://translate.google.com/#en/vi/" + text); string result = driver.FindElementById("result_box").Text; return(Content(result)); }
static void AccessEuroNext() { List <Target> stockList = AccessFiles.getList(StockName.EURONEXT); foreach (var stock in stockList) { Console.WriteLine(stock.urlIdentifier); } GlobalQuote mytempQuery = AccessXIgnite.getXigniteData("XNAS", "a"); using (PhantomJSDriver driver = new PhantomJSDriver(@"C:\phantomjs-2.1.1-windows\bin")) { foreach (Target stock in stockList) { driver.Url = stock.urlIdentifier; driver.Navigate(); System.Threading.Thread.Sleep(3 * 1000); Instrument myInstrument = new Instrument(); { try { myInstrument.PctChange(driver.FindElementById("cnDiffRelvalue").Text.Replace("(", string.Empty).Replace(")", string.Empty)); myInstrument.Change(driver.FindElementById("cnDiffAbsvalue").Text); myInstrument.LastPrice(driver.FindElementById("lastPriceint").Text + driver.FindElementById("lastPricefract").Text); myInstrument.DayHigh(driver.FindElementById("highPricevalue").Text.Split('[')[0]); myInstrument.DayLow(driver.FindElementById("lowPricevalue").Text.Split('[')[0]); string b = driver.FindElementById("todayVolumevalue").Text.Split('[')[0]; myInstrument.Volume(driver.FindElementById("todayVolumevalue").Text.Split('[')[0]); //myInstrument.PrevClose(table.FindElement(By.ClassName("op")).Text); myInstrument.Bid(driver.FindElementById("bidPricevalue").Text); myInstrument.Ask(driver.FindElementById("askPricevalue").Text); myInstrument.ticker = stock.shortIdentifier; myInstrument.timestamp = System.DateTime.Now; myInstrument.stockExchangeName = StockName.EURONEXT; myInstrument.url = stock.urlIdentifier; } catch { } } InstrumentContext ctx = new InstrumentContext(); ctx.Instruments.InsertOne(myInstrument); } } }
public string TranslateChat(string sentence, ClientLanguage from) { if (IronworksSettings.Instance == null) { throw new Exception("IronworksSettings is null"); } string tk = "ko"; foreach (var item in LanguageCodeList.papago) { if (IronworksSettings.Instance.Translator.NativeLanguage.ToString().Equals(item.NameEnglish)) { tk = item.Code; } } string sk = "ja"; foreach (var item in LanguageCodeList.papago) { if (from.ToString().Equals(item.NameEnglish)) { sk = item.Code; } } string testUrl = $"https://papago.naver.com/?sk={sk}&tk={tk}&st={Uri.EscapeDataString(sentence)}"; lock (driver) { //Log.Debug($"Translate URL: {testUrl}"); Log.Debug($"Locked web browser for {sentence}"); driver.Url = testUrl; driver.Navigate(); //the driver can now provide you with what you need (it will execute the script) //get the source of the page //var source = driver.PageSource; string translated = string.Copy(sentence); //fully navigate the dom try { OpenQA.Selenium.IWebElement pathElement; do { pathElement = driver.FindElementById("txtTarget"); } while (pathElement.Text.Equals("")); translated = pathElement.Text; Log.Debug($"Successfully translated {sentence} -> {translated}"); } catch (Exception e) { Log.Error($"Exception {e.Message} when translating {sentence}"); translated = translated.Insert(0, "[원문]"); } return(translated); } }
public void Index() { // TODO: put the development environment url const string baseUrl = ""; var driver = new PhantomJSDriver(); driver.Navigate().GoToUrl(baseUrl); var element = driver.FindElementById("learn_more"); element.Should().NotBeNull(); }
/// <summary> /// Test implementation /// </summary> /// <param name="URL">URL to test</param> /// <returns></returns> public static string Test(string URL) { // Initialize the Chrome Driver // Place phantomjs.exe driver in the project root, // meaning same folder as WebRole.cs using (var driver = new PhantomJSDriver()) { try { // Go to the home page driver.Navigate().GoToUrl(URL); IWebElement input; WebDriverWait wait = new WebDriverWait( driver, TimeSpan.FromSeconds(2)); Func <IWebDriver, IWebElement> _emailInputIsVisible = ExpectedConditions.ElementIsVisible(By.Id("email")); wait.Until(_emailInputIsVisible); input = driver.FindElementById("email"); input.SendKeys("*****@*****.**"); driver.FindElementById("submit").Click(); var alertbox = driver.FindElementById("alert"); if (alertbox.Text.Contains("disposable")) { return("PASS"); } else { return("FAIL: alertbox.Text should contain " + "the word 'disposable'"); } } catch (Exception ex) { return($"FAIL: {ex.Message}"); } } }
static void Main(string[] args) { PhantomJSDriver driver = new PhantomJSDriver(); driver.Manage().Window.Maximize(); driver.Navigate().GoToUrl("http://sampleapp.tricentis.com/101/"); driver.GetScreenshot().SaveAsFile("screenshot1.png", ScreenshotImageFormat.Png); IWebElement btnTruck = driver.FindElementById("nav_truck"); btnTruck.Click(); driver.GetScreenshot().SaveAsFile("screenshot2.png", ScreenshotImageFormat.Png); driver.Quit(); }
private static string GetTokenFromUrl(string url, string username, string password) { var driverService = PhantomJSDriverService.CreateDefaultService(); driverService.HideCommandPromptWindow = true; driverService.LoadImages = false; driverService.SslProtocol = "tlsv1"; driverService.IgnoreSslErrors = true; driverService.ProxyType = "https"; driverService.Proxy = ""; using (var phantom = new PhantomJSDriver(driverService)) { phantom.Manage().Cookies.DeleteAllCookies(); phantom.Navigate().GoToUrl(url); var userField = phantom.FindElementById("id_username"); var passField = phantom.FindElementById("id_password"); var loginButton = phantom.FindElementByClassName("button-green"); userField.SendKeys(username); passField.SendKeys(password); loginButton.Click(); //https://www.google.es/?gws_rd=ssl#access_token=1092362346.6a5985a.584f9dfd6b88426a8e155ef68b443b2c Regex regex = new Regex(@"access_token=\S+$"); var match = regex.Match(phantom.Url); if (match.Success) { return(match.Value.Substring("access_token=".Length)); } Assert.Fail("No token found on " + phantom.Url); return(""); } }
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().SetPageLoadTimeout(TimeSpan.FromSeconds(10)); driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(20)); //driver.Url = inputURL; string source = ""; try { driver.Navigate().GoToUrl(inputURL); if (targetLink != "") { //Console.WriteLine("here"); //var firstNext = driver.FindElementByCssSelector(dropDownLink); //firstNext.Click(); //Thread.Sleep(5000); var next = driver.FindElementById(targetLink); next.Click(); Thread.Sleep(10000); } source = driver.PageSource; } catch (Exception e) { Helper.writeError(e.ToString(), (fileName + sportName)); } Helper.writePulledData(source, (fileName + sportName)); driver.Quit(); Console.WriteLine("Data pulled"); }
public override bool Execute(PhantomJSDriver driver) { IWebElement element = null; switch (Parameters[0]) { case "id": element = driver.FindElementById(Parameters[1]); break; case "class": element = driver.FindElementByClassName(Parameters[1]); break; case "tag": element = driver.FindElementByTagName(Parameters[1]); break; case "text": element = driver.FindElementByLinkText(Parameters[1]); break; case "name": element = driver.FindElementByName(Parameters[1]); break; default: return(false); } //Element not found if (element == null) { return(false); } try { element.Click(); return(true); } catch (Exception e) { return(false); //Element not clickable } }
public override bool Execute(PhantomJSDriver driver) { IWebElement element = null; try { switch (Parameters[0]) { case "id": element = driver.FindElementById(Parameters[1]); break; case "class": element = driver.FindElementByClassName(Parameters[1]); break; case "name": element = driver.FindElementByName(Parameters[1]); break; } } catch (Exception e) { //Element was not found return(false); } //Wrong parameters used if (element == null) { return(false); } try { element.SendKeys(Parameters[2]); return(true); } catch (Exception e) { //ERROR element not editable/interactable return(false); } }
public void OpenUrl(PhantomJSDriver driver, string Url) { driver.Navigate().GoToUrl(Url); try { var searchInputBar = driver.FindElementById("keyword");//grab the pages search input Console.WriteLine("Begining Search"); searchInputBar.Click(); while (true) { //grab item to search for from the command pompt Console.WriteLine("What Shoes Are You Looking For:"); var SearchFor = Console.ReadLine(); if (SearchFor == null || SearchFor == string.Empty) { Console.WriteLine("Invalid Search Type"); } else { Console.WriteLine("Begin Search For " + SearchFor); searchInputBar.SendKeys(SearchFor); //input search values searchInputBar.SendKeys(Keys.Enter); //begin search break; } } } catch (Exception ex) { Console.WriteLine("We had a problem searching! " + ex.Message); } }
/// <summary> /// select shoe size and add to cart /// </summary> /// <param name="driver"></param> /// <param name="wait"></param> public void SelectShoeSize(PhantomJSDriver driver, WebDriverWait wait) { var SizeDropDown = driver.FindElementById("pdp_size_select"); SizeDropDown.Click(); wait.Until((_driver) => { return(ExpectedConditions.ElementIsVisible(By.ClassName("product_sizes_content"))); }); var ShoeSize = new List <IWebElement>(driver.FindElementsByTagName("a")); var SelectedShoeSize = ShoeSize.Find((ele) => { return(ele.GetAttribute("data-modelsize") == "11_0"); });//TODO Select from File var AddToCart = new List <IWebElement>(driver.FindElementsByTagName("button")).Find((ele) => { return(ele.GetAttribute("title") == "Add To Cart"); }); if (SelectedShoeSize != null) { //Add To cart SelectedShoeSize.Click(); Thread.Sleep(TimeSpan.FromSeconds(2)); AddToCart.Click(); Console.WriteLine("Added to Cart! "); } }
public static PlayerHeroesPreferenceModel ScrapeHeroPreferencesPhantomJs(string playerId, int days = 60) { if (string.IsNullOrWhiteSpace(playerId)) { return(null); } var retries = 5; while (--retries > 0) { try { using (var driver = new PhantomJSDriver()) { var url = BuildPlayerStatsUrl(playerId); driver.Navigate().GoToUrl(url); // Open the 'Days to show' selector driver.FindElementById("ctl00_MainContent_DropDownProfileTimeSpan").Click(); var daySelectParent = new WebDriverWait(driver, TimeSpan.FromSeconds(2)).Until(e => { var elem = e.FindElement(By.Id("ctl00_MainContent_DropDownProfileTimeSpan_DropDown")); return(elem.GetAttribute("style").Contains("display: block;") ? elem : null); }); // Select the 'Last X Days' option to show only heroes played in the last so many days var daySelectText = $"Last {days} Days"; daySelectParent.FindElements(By.CssSelector("li")).First(e => e.Text == daySelectText).Click(); // Do the same for the range (i.e. only show heroes that have been played more than x times) driver.FindElementById("ctl00_MainContent_DropDownGamesPlayedRequired").Click(); var rangeSelectParent = new WebDriverWait(driver, TimeSpan.FromSeconds(2)).Until(e => { var elem = e.FindElement(By.Id("ctl00_MainContent_DropDownGamesPlayedRequired_DropDown")); return(elem.GetAttribute("style").Contains("display: block;") ? elem : null); }); var rangeSelectText = "5+ Games Played"; new WebDriverWait(driver, TimeSpan.FromSeconds(2)).Until(e => { var elem = rangeSelectParent.FindElements(By.CssSelector("li")).FirstOrDefault(li => li.Text == rangeSelectText); return(elem ?? elem); }).Click(); // Find the hero stats in the table and parse the stats out var rows = driver.FindElementsByCssSelector("#RadGridReplayCharacterScoreResultsAverage table tbody tr"); var stats = new List <HeroStatsModel>(); foreach (var row in rows) { var dataElems = row.FindElements(By.TagName("td")); var heroNameElem = dataElems[0]; var gamesPlayedElem = dataElems[2]; var winPercentElem = dataElems[3]; var heroName = heroNameElem.FindElement(By.TagName("a")).GetAttribute("title"); var gamesPlayed = gamesPlayedElem.Text; var winPercent = winPercentElem.Text.Replace("%", ""); stats.Add(new HeroStatsModel { Name = WebUtility.HtmlDecode(heroName), GamesPlayed = Convert.ToInt32(gamesPlayed), WinPercent = Convert.ToDouble(winPercent) }); } return(new PlayerHeroesPreferenceModel { HeroStats = stats.OrderByDescending(e => e.GamesPlayed).ThenByDescending(e => e.WinPercent).ToList(), PlayerId = playerId }); } } catch (StaleElementReferenceException) { continue; } catch { return(new PlayerHeroesPreferenceModel { HeroStats = new List <HeroStatsModel>(), PlayerId = playerId }); } } return(new PlayerHeroesPreferenceModel { HeroStats = new List <HeroStatsModel>(), PlayerId = playerId }); }
static void Main(string[] args) { if (args.Length < 2) { Console.WriteLine("SoloLearn username password"); Environment.Exit(1); } string userName = args[0]; string passWord = args[1]; Dictionary <string, int> countries = GetCountries(); var driver = new PhantomJSDriver(); driver.Navigate().GoToUrl(loginUrl); var userID = driver.FindElementById("Email"); userID.Clear(); userID.SendKeys(userName); var passID = driver.FindElementById("Password"); passID.Clear(); passID.SendKeys(passWord); var form = driver.FindElementByTagName("form"); form.Submit(); driver.Navigate().GoToUrl(scrapeUrl); int delay = 3000; // 3 seconds var javascriptInBrowser = (IJavaScriptExecutor)driver; var detailsWrapper = driver.FindElementsByClassName("detailsWrapper"); var lastDetailsWrapperCount = detailsWrapper.Count; while (true) { javascriptInBrowser.ExecuteScript("arguments[0].scrollIntoView(true);", detailsWrapper[lastDetailsWrapperCount - 1]); Thread.Sleep(delay); detailsWrapper = driver.FindElementsByClassName("detailsWrapper"); if (detailsWrapper.Count == lastDetailsWrapperCount) { break; } else { lastDetailsWrapperCount = detailsWrapper.Count; delay += 500; // add 1/2 a second to the delay } } string text = string.Empty; foreach (var detail in detailsWrapper) { text = detail.GetAttribute("innerText").ToUpperInvariant(); foreach (KeyValuePair <string, int> kvp in countries) { if (text.Contains(kvp.Key.ToUpperInvariant())) { countries[kvp.Key] += 1; break; // don't look for multiple matches } } } driver.Quit(); driver.Dispose(); var items = from pair in countries orderby pair.Value descending select pair; foreach (KeyValuePair <string, int> kvp in items) { Console.WriteLine("{0}\t{1}", kvp.Key, kvp.Value); } }
public HblBank(string Username, string Password) { try { driver.Navigate().GoToUrl("https://hblibank.com.pk/"); } catch { throw new Exception("(ErrorCode:1) Bank Service Unavailable Or Network Not Available"); } try { driver.FindElementById("btnProceed").Click(); driver.FindElementByName("fldLoginUserId").SendKeys(Username); driver.FindElementByName("fldPassword").SendKeys(Password); driver.FindElementById("foo").Click(); ReadOnlyCollection <String> handles = driver.WindowHandles; driver.SwitchTo().Window(handles[0]); } catch { throw new Exception("(ErrorCode:2) Service Response Delay"); } try { driver.SwitchTo().Frame("frame_menu"); driver.FindElementById("RRAAClink").Click(); } catch { throw new Exception("(ErrorCode:3) Credentials are not Valid Or Network Not Available"); } try { driver.SwitchTo().Window(driver.CurrentWindowHandle); driver.SwitchTo().Frame("frame_txn"); string abc = driver.FindElementByName("fldacctno").GetAttribute("innerHTML"); Document body = Supremes.Dcsoup.Parse(abc); Elements options = body.Select("option"); Accounts = new List <Account>(); foreach (Element el in options) { if (!el.Val.Equals("")) { Accounts.Add(new Account(driver) { Name = el.OwnText, Value = el.Val }); } } } catch { throw new Exception("(ErrorCode:4) Network Or Service not Available"); } }
public void Register_Invalid_inputs() { try { _driver.Manage().Timeouts().SetPageLoadTimeout(TimeSpan.FromSeconds(30)); _driver.Navigate().GoToUrl("http://localhost:5000/Login/Register"); IWebElement btnsubmit = _driver.FindElementById("btnhtregistration"); btnsubmit.Submit(); IWebElement fnameerror = _driver.FindElementById("Fname-error"); IWebElement lnameerror = _driver.FindElementById("Lname-error"); IWebElement phoneerror = _driver.FindElementById("Phone-error"); IWebElement mailerror = _driver.FindElementById("EmailID-error"); IWebElement passerror = _driver.FindElementById("Password-error"); IWebElement conpasserror = _driver.FindElementById("ConfirmPassword-error"); IWebElement addresserror = _driver.FindElementById("Address-error"); Assert.AreEqual("First Name is required", fnameerror.GetAttribute("textContent")); Assert.AreEqual("Last Name is required", lnameerror.GetAttribute("textContent")); Assert.AreEqual("Email ID is required", mailerror.GetAttribute("textContent")); Assert.AreEqual("Password is required", passerror.GetAttribute("textContent")); Assert.AreEqual("Confirm Password is required", conpasserror.GetAttribute("textContent")); Assert.AreEqual("Mobile is required", phoneerror.GetAttribute("textContent")); Assert.AreEqual("Address is required", addresserror.GetAttribute("textContent")); Console.Out.WriteLine("Required field validation succeed"); IWebElement txtphone = _driver.FindElement(By.Id("Phone")); IWebElement txtmail = _driver.FindElement(By.Id("EmailID")); txtphone.SendKeys("123456"); txtmail.SendKeys("rohilla"); txtmail.SendKeys(Keys.Tab); Assert.AreEqual("PhoneNumber should contain only numbers and must be 10 digits long", phoneerror.GetAttribute("textContent")); Assert.AreEqual("Please enter a valid email address", mailerror.GetAttribute("textContent")); Console.Out.WriteLine("Phone and email error check is succeed"); } catch (Exception ex) { Console.Out.WriteLine(ex.Message); } }
public AccountStatement GetAccountStatement(DateTime From, DateTime To) { if (driver != null) { try { driver.SwitchTo().Window(driver.CurrentWindowHandle); driver.SwitchTo().Frame("frame_menu"); driver.FindElementById("RRAAClink").Click(); driver.SwitchTo().Window(driver.CurrentWindowHandle); driver.SwitchTo().Frame("frame_txn"); SelectElement elem = new SelectElement(driver.FindElementByName("fldacctno")); elem.SelectByValue(this.Account_Value); //driver.SwitchTo().Window(driver.CurrentWindowHandle); //driver.SwitchTo().Frame("frame_txn"); var abcd = driver.FindElementsByClassName("objselect"); SelectElement elem2 = new SelectElement(abcd[1]); elem2.SelectByValue("3"); driver.FindElementById("fldfromdateid").SendKeys(From.ToString("dd-MM-yyyy")); driver.FindElementById("fldtodateid").SendKeys(To.ToString("dd-MM-yyyy")); driver.FindElementByName("fldsubmit").Click(); var alltables = driver.FindElementsByClassName("graphtable"); string abc = alltables[0].GetAttribute("innerHTML"); Document body = Supremes.Dcsoup.Parse(abc); AccountStatement statement = new AccountStatement(); statement.OpeningBalance = HelpingClass.ToDouble(body.Body.TextNodes[4].Text); statement.ClosingBalance = HelpingClass.ToDouble(body.Body.TextNodes[5].Text); abc = alltables[1].GetAttribute("innerHTML"); body = Supremes.Dcsoup.ParseBodyFragment("<table>" + abc + "</table>"); List <AccountActivity> activities = new List <AccountActivity>(); AccountActivity activity = new AccountActivity(); Elements trs = body.Select("tr"); Elements tds = null; bool isavilable = false; abc = driver.FindElementByClassName("standardtable").GetAttribute("innerHTML"); body = Supremes.Dcsoup.ParseBodyFragment("<table>" + abc + "</table>"); string[] arr = body.Body.Text.Split(new string[] { "Pages : (" }, StringSplitOptions.None); int totalpage = Convert.ToInt32(arr[1].Split(')')[0].Trim()); int currentpage = 1; do { for (int i = 0; i < trs.Count; i++) { if (i != 0) { tds = trs[i].Select("td"); activity = new AccountActivity(); activity.TransactionDate = DateTime.ParseExact(tds[0].OwnText, "dd-MM-yyyy", CultureInfo.InvariantCulture); activity.ValueDate = DateTime.ParseExact(tds[1].OwnText, "dd-MM-yyyy", CultureInfo.InvariantCulture); activity.TransactionReferenceNo = tds[2].OwnText; activity.Description = tds[3].OwnText; activity.Debit = HelpingClass.ToDouble(tds[4].OwnText); activity.Credit = HelpingClass.ToDouble(tds[5].OwnText); activity.Balance = HelpingClass.ToDouble(tds[6].OwnText); activities.Add(activity); } } if (currentpage < totalpage) { currentpage++; driver.FindElementByCssSelector("a[href=\"javascript:SendPageRequest(" + currentpage.ToString() + ")\"]").Click(); alltables = driver.FindElementsByClassName("graphtable"); abc = alltables[1].GetAttribute("innerHTML"); body = Supremes.Dcsoup.ParseBodyFragment("<table>" + abc + "</table>"); trs = body.Select("tr"); isavilable = true; } else { isavilable = false; } } while (isavilable); statement.Activities = activities.AsReadOnly(); return(statement); } catch { throw new Exception("(ErrorCode:11) Network Or Service is not available Or May be Problem occured While Fetching Account Details Try Again.."); } } else { throw new Exception("(ErrorCode:10) Account Detail object not initialized"); } }
public override void DownloadFile(string temporaryFilePath, ILogger logger) { logger?.Info("Downloading account statements from Easybank ..."); using (var driverService = PhantomJSDriverService.CreateDefaultService()) { driverService.HideCommandPromptWindow = true; using (var driver = new PhantomJSDriver(driverService)) { driver.Manage().Timeouts().SetPageLoadTimeout(TimeSpan.FromSeconds(60)); driver.Manage().Timeouts().SetScriptTimeout(TimeSpan.FromSeconds(60)); driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(60)); try { logger?.Trace("Opening Easybank homepage ..."); driver.Navigate().GoToUrl("https://ebanking.easybank.at"); Screenshot(driver, "Easybank-1", logger); logger?.Trace("Filling login credentials ..."); driver.FindElementById("lof5").SendKeys(_configuration.Verfuegernummer); driver.FindElementById("lof9").SendKeys(_configuration.Pin); driver.FindElementByLinkText("Login").Click(); Screenshot(driver, "Easybank-2", logger); logger?.Trace("Loading account overview ..."); driver.FindElementByLinkText(_configuration.Kontonummer).Click(); Screenshot(driver, "Easybank-3", logger); logger?.Info("Injecting & executing JavaScript ..."); const string script = "var resultField = $('<pre />').attr('id', 'csv_result');" + "var form = document.transactionSearchForm;" + "form.csv.value = 'true';" + "$.ajax({ url: $(form).attr('action')," + "type: 'post'," + "data: $(form).serialize()," + "error: function(xhr, status, error) {" + "$('body').html('').append(resultField);" + "resultField.html('AJAX request failed: ' + status + ' / ' + error);" + "}," + "success: function(response) {" + "$('body').html('').append(resultField);" + "resultField.html(response);" + "}});"; driver.ExecuteScript(script); logger?.Trace("Loading file content from page and saving to {0} ...", temporaryFilePath); var text = driver.FindElementById("csv_result").Text; Screenshot(driver, "Easybank-4", logger); using (var writer = new StreamWriter(temporaryFilePath, false, Encoding.UTF8)) { writer.Write(text); } logger?.Trace("Download completed."); } catch (Exception ex) { logger?.Error("Unable to download from Easybank: " + ex); } finally { driver.Quit(); } } } }