public void ListWindows(out List windows, out List handles) { handles = WindowContext.GetWindowsHandles(_session); windows = new List(handles.Count); foreach (string handle in handles) { int hash = handle.GetHashCode(); foreach (Window win in _cachedWindows) { if (win.GetHashCode() == hash && handle == win.Handle) { windows.Add(win); goto nextHandle; } } windows.Add(new Window(_session, this, handle)); nextHandle: continue; } _cachedWindows = windows; }
public WindowContext(RemoteSession session) : base() { _session = session; _currentWindow = new Window(session, this, null); _previousWindow = _currentWindow; _cachedWindows = new List(10); _cachedWindows.Add(_currentWindow); }
public void Manipulate() { ChromeDriver driver = new ChromeDriver(); HelpFunctions H = new HelpFunctions(); H.Navigate("http://us14.chatzy.com/37785015405504", driver); H.Navigate("http://us14.chatzy.com", driver); driver.Manage().Timeouts().ImplicitlyWait(new TimeSpan(0, 0, 100)); WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(5)); IWebElement element = null; //= wait.Until(ExpectedConditions.ElementIsVisible(By.ClassName("X967"))); H.Button("//*[@id='X313']", driver);//Login/SignUp driver.Manage().Timeouts().ImplicitlyWait(new TimeSpan(0, 0, 30)); element = wait.Until(ExpectedConditions.ElementIsVisible(By.XPath("//*[@id='X603']"))); H.InputInfo("//*[@id='X603']", "*****@*****.**", driver);//add email driver.Manage().Timeouts().ImplicitlyWait(new TimeSpan(0, 0, 30)); H.Button("//*[@id='X6001']", driver); // choose the "I am regitered user" driver.Manage().Timeouts().ImplicitlyWait(new TimeSpan(0, 0, 30)); H.InputInfo("//*[@id='X604']", "Amber001", driver); //Enter in the password driver.Manage().Timeouts().ImplicitlyWait(new TimeSpan(0, 0, 30)); H.Button("//*[@id='X593']", driver); //click the ok button element = wait.Until(ExpectedConditions.ElementIsVisible(By.ClassName("X967"))); H.Navigate("http://us14.chatzy.com/37785015405504", driver); H.Button("//*[@id='X593']", driver); //click the enter room button H.Button("//*[@id='X1049']", driver); var chat = driver.FindElementById("X184"); // System.Collections.ObjectModel.ReadOnlyCollection<IWebElement> chat = driver.FindElementsByClassName("a"); // chat.ToString(); List<string> Temp = new List<string>(); Temp.Add(chat.Text); System.IO.File.AppendAllLines(@"OUTPUT3.txt", Temp); string[] t = System.IO.File.ReadAllLines(@"OUTPUT3.txt"); t.ToList(); // string s = chat.Text; // string[] words = Regex.Split(s, "\r\n"); driver.Close(); }
static void Main(string[] args) { try { string baseUrl = "http://www.amazon.com/"; if (args.Length >= 1) { baseUrl = args[0]; } string filename; if (args.Length >= 2) { filename = args[1]; } else { Uri uri = new Uri(baseUrl); filename = uri.Host.Replace(".", "-") + @".har"; } // Uncomment to enable SSL support // Fiddler.CONFIG.IgnoreServerCertErrors = true; // FiddlerApplication.Prefs.SetBoolPref("fiddler.network.streaming.abortifclientaborts", true); // Varibale to store the list of items downloaded var sessions = new List<Fiddler.Session>(); var newSessions = new List<Fiddler.Session>(); int browserProcessId = -1; // As each HTTP item is downloaded add it to our list. // We will export this list later. Fiddler.FiddlerApplication.AfterSessionComplete += delegate(Fiddler.Session oS) { Monitor.Enter(sessions); // Only record HTTP traffic by our browser process if (browserProcessId == oS.LocalProcessID) { sessions.Add(oS); } Monitor.Exit(sessions); }; Fiddler.FiddlerApplication.BeforeRequest += delegate(Fiddler.Session oS) { // Record the process id for the first URL we go to, // this is the browser that we lanched with Selenium // Could also do extra verification here, for example // check that it is a child process, of this process. // That requires some heavy Win32 API usage, so I've // skipped it here. if (browserProcessId == -1 && oS.fullUrl == baseUrl) { browserProcessId = oS.LocalProcessID; } // Only record HTTP traffic by our browser process if (browserProcessId == oS.LocalProcessID) { Monitor.Enter(newSessions); newSessions.Add(oS); Monitor.Exit(newSessions); } }; // Start Fiddler on port 8877. // Register as the system wide proxy. Fiddler.FiddlerApplication.Startup(8877, FiddlerCoreStartupFlags.Default); ///////////////////////////////////////////////// // Begin selenium test ///////////////////////////////////////////////// var webDriver = new OpenQA.Selenium.Firefox.FirefoxDriver(); var selenium = new Selenium.WebDriverBackedSelenium(webDriver, baseUrl); selenium.Start(); selenium.Open(baseUrl); // Wait until 3 seconds of HTTP idle (no request being processed for 3 seconds) // or a 30 second timeout. // 'result' will be false if items are still being downloaded when the timeout // occurs. bool result = WaitHttpIdle(sessions, 3000, 30000); selenium.Stop(); ///////////////////////////////////////////////// // End selenium test ///////////////////////////////////////////////// // Load the HAR file exporter (this only has to be done once per process). // The following DLL was downloaded from: // https://www.fiddler2.com/dl/FiddlerCore-BasicFormats.zip // It is currently only loadable with FiddlerCode 2.2.9.9. String path = Path.Combine(Path.GetDirectoryName (Assembly.GetExecutingAssembly().Location), @"FiddlerCore-BasicFormats.dll"); FiddlerApplication.oTranscoders.ImportTranscoders(path); // Export fiddler sessions to HAR file Monitor.Enter(sessions); var oExportOptions = new Dictionary<string, object>(); oExportOptions.Add("Filename", filename); bool fiddler = Fiddler.FiddlerApplication.DoExport("HTTPArchive v1.2", sessions.ToArray(), oExportOptions, null); sessions.Clear(); Monitor.Exit(sessions); } finally { // Shutdown fiddler, this removes Fiddler as the system proxy. Fiddler.FiddlerApplication.Shutdown(); Thread.Sleep(500); } }
static void Main(string[] args) { try { string baseUrl = "http://www.webmetrics.com"; if (args.Length >= 1) { baseUrl = args[0]; } string filename; if (args.Length >= 2) { filename = args[1]; } else { Uri uri = new Uri(baseUrl); filename = uri.Host.Replace(".", "-") + @".har"; } // Uncomment to enable SSL support // Fiddler.CONFIG.IgnoreServerCertErrors = true; // FiddlerApplication.Prefs.SetBoolPref("fiddler.network.streaming.abortifclientaborts", true); // Varibale to store the list of items downloaded var sessions = new List<Fiddler.Session>(); // As each HTTP item is downloaded add it to our list. // We will export this list later. Fiddler.FiddlerApplication.AfterSessionComplete += delegate(Fiddler.Session oS) { Monitor.Enter(sessions); sessions.Add(oS); Monitor.Exit(sessions); }; // As each HTTP item is downloaded add it to our list. // We will export this list later. Fiddler.FiddlerApplication.BeforeRequest += delegate(Fiddler.Session oS) { if (!new Regex(baseUrl).IsMatch(oS.fullUrl)) { oS.utilCreateResponseAndBypassServer(); oS.responseCode = 200; } }; // Start Fiddler on port 8877. // Register as the system wide proxy. Fiddler.FiddlerApplication.Startup(8877, FiddlerCoreStartupFlags.Default); ///////////////////////////////////////////////// // Begin selenium test ///////////////////////////////////////////////// var webDriver = new OpenQA.Selenium.Firefox.FirefoxDriver(); var selenium = new Selenium.WebDriverBackedSelenium(webDriver, baseUrl); selenium.Start(); selenium.Open(baseUrl); selenium.WaitForPageToLoad("30000"); selenium.Stop(); ///////////////////////////////////////////////// // End selenium test ///////////////////////////////////////////////// // Load the HAR file exporter (this only has to be done once per process). // The following DLL was downloaded from: // https://www.fiddler2.com/dl/FiddlerCore-BasicFormats.zip // It is currently only loadable with FiddlerCode 2.2.9.9. String path = Path.Combine(Path.GetDirectoryName (Assembly.GetExecutingAssembly().Location), @"FiddlerCore-BasicFormats.dll"); FiddlerApplication.oTranscoders.ImportTranscoders(path); // Export fiddler sessions to HAR file Monitor.Enter(sessions); var oExportOptions = new Dictionary<string, object>(); oExportOptions.Add("Filename", filename); bool fiddler = Fiddler.FiddlerApplication.DoExport("HTTPArchive v1.2", sessions.ToArray(), oExportOptions, null); sessions.Clear(); Monitor.Exit(sessions); } finally { // Shutdown fiddler, this removes Fiddler as the system proxy. Fiddler.FiddlerApplication.Shutdown(); Thread.Sleep(500); } }
static void LoadFile(ref List<string> l, ref Dictionary<string,string> dict) { try { //declare variable string line; List<string> listStrLineElements = new List<string>(); //calling steamreader and reading the numbers from Numbers.txt using (StreamReader sr = new StreamReader("Keywords.txt")) { while ((line = sr.ReadLine()) != null) { if (line == null) { break; } #region Split into name and keywords from the input file listStrLineElements = line.Split(',').ToList(); for (int i = 0; i < listStrLineElements.Count; i++) { switch (i) { case 0: l.Add(listStrLineElements[i]); break; case 1: dict.Add(listStrLineElements[(i-1)], listStrLineElements[i]); break; default: break; } } #endregion } } } catch (Exception LoadFile) { MessageBox.Show("Load File Error: " + LoadFile.Message); } }
static void Main(string[] args) { //Declaration //l = phone numbers, quotation number, desc of the records, entity, submission date , submission time, name of user List<string> l = new List<string>(); List<string> quotation = new List<string>(); List<string> desc = new List<string>(); List<string> entity = new List<string>(); List<string> subDate = new List<string>(); List<string> subTime = new List<string>(); List<string> name = new List<string>(); List<string> kw = new List<string>(); Dictionary<string, string> dict = new Dictionary<string, string>(); int numbrecords = 0; string filename = ""; #region Load google chrome // Initialize the Chrome Driver using (var driver = new ChromeDriver()) { LoadFile(ref l, ref dict); // Go to the home page driver.Navigate().GoToUrl("http://www.gebiz.gov.sg/scripts/main.do?sourceLocation=openarea&select=tenderId"); #region autofill and extract data from GeBiz webpage foreach (var val in l) { //Get the page elements var fromdate = driver.FindElementByXPath("/html/body/table/tbody/tr[2]/td[2]/table/tbody/tr[2]/td/form/table[2]/tbody/tr/td/table/tbody/tr[2]/td/table/tbody/tr[5]/td[4]/input"); var todate = driver.FindElementByXPath("/html/body/table/tbody/tr[2]/td[2]/table/tbody/tr[2]/td/form/table[2]/tbody/tr/td/table/tbody/tr[2]/td/table/tbody/tr[5]/td[6]/input"); var keyword = driver.FindElementByName("searchByDesc"); new SelectElement(driver.FindElement(By.Name("dateType"))).SelectByIndex(1); var submitbutton = driver.FindElementByName("submitAction"); fromdate.SendKeys(DateTime.Now.AddDays(-1).ToString("dd/MM/yyyy")); todate.SendKeys(DateTime.Now.AddDays(-1).ToString("dd/MM/yyyy")); keyword.SendKeys(val); //click the submit button submitbutton.Click(); if (driver.FindElements(By.XPath("/html/body/table/tbody/tr[2]/td[2]/table/tbody/tr[2]/td/form/table[3]/tbody/tr/td/table[1]/tbody/tr[2]/td")).Count == 1) { driver.Navigate().GoToUrl("http://www.gebiz.gov.sg/scripts/main.do?sourceLocation=openarea&select=tenderId"); } else { if (driver.FindElementByXPath("/html/body/table/tbody/tr[2]/td[2]/table/tbody/tr[2]/td/form/table[3]/tbody/tr/td/table[1]/tbody/tr[2]/td").Text.Equals("No data found")) { Console.WriteLine("No Data Found"); driver.Navigate().GoToUrl("http://www.gebiz.gov.sg/scripts/main.do?sourceLocation=openarea&select=tenderId"); } else { #region Checking the number of records for (int j = 11; j > 1; j--) { //select the records by row if (driver.FindElements(By.XPath("/html/body/table/tbody/tr[2]/td[2]/table/tbody/tr[2]/td/form/table[3]/tbody/tr/td/table[1]/tbody/tr[" + j + "]")).Count == 1) { Console.WriteLine(driver.FindElementByXPath("/html/body/table/tbody/tr[2]/td[2]/table/tbody/tr[2]/td/form/table[3]/tbody/tr/td/table[1]/tbody/tr[2]/td").Text); numbrecords = j + 1; #region Storing quotation and desc to list for (int i = 2; i < numbrecords; i++) { //get the record from the current row on the quotation col quotation.Add(driver.FindElementByXPath("/html/body/table/tbody/tr[2]/td[2]/table/tbody/tr[2]/td/form/table[3]/tbody/tr/td/table[1]/tbody/tr[" + i + "]/td[2]/table/tbody/tr[1]/td/a/b").Text); //get the record from the current row on the description col desc.Add(driver.FindElementByXPath("/html/body/table/tbody/tr[2]/td[2]/table/tbody/tr[2]/td/form/table[3]/tbody/tr/td/table[1]/tbody/tr[" + i + "]/td[3]/table/tbody/tr[1]/td").Text); //get the record from the current row on entity from description col entity.Add(RemoveWord(driver.FindElementByXPath("/html/body/table/tbody/tr[2]/td[2]/table/tbody/tr[2]/td/form/table[3]/tbody/tr/td/table[1]/tbody/tr[" + i + "]/td[3]/table/tbody/tr[2]/td").Text)); //get the record from the current row on submission date from closing date/time col subDate.Add(driver.FindElementByXPath("/html/body/table/tbody/tr[2]/td[2]/table/tbody/tr[2]/td/form/table[3]/tbody/tr/td/table[1]/tbody/tr[" + i + "]/td[5]/table/tbody/tr[1]/td").Text); //get the record from the current row on submission time from closing date/time col subTime.Add(driver.FindElementByXPath("/html/body/table/tbody/tr[2]/td[2]/table/tbody/tr[2]/td/form/table[3]/tbody/tr/td/table[1]/tbody/tr[" + i + "]/td[5]/table/tbody/tr[2]/td").Text); //add the name of the organisation that the keyword belong to name.Add(dict[val]); //add the keyword kw.Add(val); } driver.Navigate().GoToUrl("http://www.gebiz.gov.sg/scripts/main.do?sourceLocation=openarea&select=tenderId"); break; #endregion } } #endregion } } } #endregion } #endregion //saving to excel file filename = SaveExcel(); ExportData(filename, ref quotation, ref desc, ref entity, ref subDate, ref subTime, ref name, ref kw); }
/// <summary> /// Returns a list containing the text parsed to a number for each element /// </summary> /// <param name="defaultValue">Default value in case the text can't be parsed.</param> /// <param name="offsetStart"></param> /// <param name="offsetEnd"></param> /// <returns></returns> public List Values(object defaultValue = null, int offsetStart = 0, int offsetEnd = 0) { int size = base.Count; int imin = offsetStart; int imax = size - 1 + offsetEnd; List lst = new List(size - offsetStart + offsetEnd); int i = -1; foreach (WebElement ele in this) { if (++i < imin || i > imax) continue; string text = ele.Text().Trim(); double num; if (double.TryParse(text, out num)) { lst.Add(num); } else { lst.Add(defaultValue); } } return lst; }
/// <summary> /// Returns a list containing the text for each element /// </summary> /// <param name="offsetStart"></param> /// <param name="offsetEnd"></param> /// <param name="trim"></param> /// <returns></returns> public List Text(int offsetStart = 0, int offsetEnd = 0, bool trim = true) { int size = base.Count; int imax = size + offsetEnd - 1; int imin = offsetStart; List lst = new List(size - offsetStart + offsetEnd); int i = -1; foreach (WebElement ele in this) { if (++i < imin || i > imax) continue; var text = ele.Text(); if (trim) { lst.Add(text.Trim()); } else { lst.Add(text); } } return lst; }
static void Main(string[] args) { HtmlDocument doc = new HtmlDocument(); List<string> list = new List<string>(); HashSet<string> listposters = new HashSet<string>(); int forumNumber = 0; string forumAddress = ""; //List<string> list = new List<string>(); ISelenium sel = new DefaultSelenium("localhost", 4444, "*chrome", forumAddress); sel.Start(); sel.WindowMaximize(); sel.Open("/"); sel.Click("id=loginlink"); sel.WaitForPageToLoad("30000"); sel.Type("id=username", ""); sel.Type("id=password", ""); sel.Click("id=submit"); sel.WaitForPageToLoad("30000"); for (int y = 1; y < 14; y++) { sel.Open(string.Format("/vbulletin/forumdisplay.php?f=" + forumNumber + "&order=desc&page={0}", y)); sel.WaitForPageToLoad("30000"); var src = sel.GetHtmlSource(); doc.LoadHtml(src); var links = doc.DocumentNode.SelectNodes("//a[@href]"); var posters = from i in links where i.OuterHtml.Contains("whoposted") select i; var ln = from o in posters select o.OuterHtml.ToString(); foreach (var item in ln) { LinkItem i = new LinkItem(); Match m2 = Regex.Match(item, @"href=\""(.*?)\""", RegexOptions.Singleline); if (m2.Success) { i.Href = m2.Groups[1].Value; } list.Add(i.Href.Replace("&", "&")); } } foreach (var it in list) { sel.Open(string.Format("vbulletin/{0}", it)); sel.WaitForPageToLoad("30000"); var src = sel.GetHtmlSource(); doc.LoadHtml(src); var links = doc.DocumentNode.SelectNodes("//a[@href]"); var posters = from i in links where i.OuterHtml.Contains("member") select i; var ln = from o in posters select o.InnerHtml.ToString(); foreach (var item in ln) { listposters.Add(item); } } sel.Close(); //var links = doc.DocumentNode.SelectNodes("//a[@href]"); //var links2 = doc.DocumentNode.G //var posters = from i in links // where i.OuterHtml.Contains("lastposter") // select i; //var link = from o in posters // select o.OuterHtml; System.IO.File.WriteAllLines(@"C:\Users\William\Documents\CsharpRandom\SeleniumTest\AllPosters.txt", listposters); Console.Read(); }
public static void Start() { Account.driver = new FirefoxDriver(); Account.Login(Account.username, Account.password); // Start village creation Account.villages = new List<Village>(); Account.driver.Navigate().GoToUrl(Account.url + "dorf1.php"); try { TimeSpan timespan = TimeSpan.FromSeconds(2); WebDriverWait wait = new WebDriverWait(Account.driver, timespan); wait.Until(ExpectedConditions.ElementIsVisible(By.Id("sidebarBoxVillagelist"))); Account.driver.FindElement(By.Id("sidebarBoxVillagelist")).FindElement(By.ClassName("addHoverClick")).Click(); ReadOnlyCollection<IWebElement> villageElements = Account.driver.FindElement(By.Id("sidebarBoxVillagelist")).FindElement(By.ClassName("sidebarBoxInnerBox")).FindElements(By.TagName("li")); string name; string id; string x; string y; int count = 0; foreach (IWebElement village in villageElements) { // Parse name and id name = Account.driver.FindElement(By.Id("sidebarBoxVillagelist")).FindElement(By.ClassName("sidebarBoxInnerBox")).FindElements(By.TagName("li"))[count].FindElement(By.ClassName("name")).Text; id = Account.driver.FindElement(By.Id("sidebarBoxVillagelist")).FindElement(By.ClassName("sidebarBoxInnerBox")).FindElements(By.TagName("li"))[count].FindElement(By.TagName("a")).GetAttribute("href"); id = id.Replace("&", "").Split('=')[1]; //Parse X x = Account.driver.FindElement(By.Id("sidebarBoxVillagelist")).FindElement(By.ClassName("sidebarBoxInnerBox")).FindElements(By.TagName("li"))[count].FindElement(By.ClassName("coordinateX")).Text; x = x.Replace("(", ""); bool negative = x.Contains('-'); x = new string(x.Where(c => char.IsDigit(c)).ToArray()); if (negative) { x = "-" + x; } //Parse Y y = Account.driver.FindElement(By.Id("sidebarBoxVillagelist")).FindElement(By.ClassName("sidebarBoxInnerBox")).FindElements(By.TagName("li"))[count].FindElement(By.ClassName("coordinateY")).Text; y = y.Replace(")", ""); negative = y.Contains('-'); y = new string(y.Where(c => char.IsDigit(c)).ToArray()); if (negative) { y = "-" + y; } Village vil = new Village(id, name, x, y); vil.setNoOfResources(); vil.setBuildingsData(); vil.setProductionPH(); vil.setResourcesData(); vil.setWareGranCapacity(); villages.Add(vil); count++; } } catch (Exception ex) { System.Windows.MessageBoxResult result = System.Windows.MessageBox.Show(ex.Message); } }