private static void RunTests() { var options = new ChromeOptions(); if (UseHeadless) { options.AddArgument("no-sandbox"); options.AddArgument("headless"); } options.AddArgument("window-size=1024x768"); using var service = string.IsNullOrEmpty(ChromeDriverPath) ? ChromeDriverService.CreateDefaultService() : ChromeDriverService.CreateDefaultService(ChromeDriverPath); using var driver = new ChromeDriver(service, options); driver.Url = Url; var index = 0; var currentTimeout = Timeout; do { var pre = driver.FindElementsByTagName("PRE").Skip(index).ToArray(); if (pre.Length > 0) { index += pre.Length; currentTimeout = Timeout; // reset the timeout foreach (var e in pre) { Console.WriteLine(e.Text); } } var resultsElement = driver.FindElementsById("results"); if (resultsElement.Count == 0) { if (driver.FindElementsByClassName("neterror").Count > 0) { var errorCode = driver.FindElementsByClassName("error-code").FirstOrDefault()?.Text; throw new Exception($"There was an error loading the page: {errorCode}"); } Thread.Sleep(500); continue; } var text = resultsElement[0].Text; var bytes = Convert.FromBase64String(text); File.WriteAllBytes(OutputPath, bytes); break; } while (--currentTimeout > 0); if (currentTimeout <= 0) { throw new TimeoutException(); } }
/// <summary> /// Crawl city pages /// </summary> /// <param name="cityList"></param> /// <returns></returns> private IList <ListingInformation> CrawlCityPages(IList <ListingInformation> cityList) { IList <ListingInformation> shelters = new List <ListingInformation>(); foreach (var city in cityList) { try { driver.Navigate().GoToUrl(city.Url); IList <IWebElement> h4Element = driver.FindElementsById("h4"); foreach (IWebElement element in h4Element) { IWebElement ele = element.FindElement(By.TagName("a")); ListingInformation shelter = new ListingInformation { Name = ele.Text, Url = ele.GetAttribute("href") }; if (!shelter.IsEmpty()) { shelters.Add(shelter); } } } catch (Exception ex) { log.LogError(ex, $"Exception while crawling shelter in state {city.Name} and url {city.Url}"); } } return(shelters); }
public void SpeechRecognized(object sender, SpeechRecognizedEventArgs e) { string video = e.Result.Semantics["Video"].Value.ToString(); //C:\Users\Darren\AppData\Local\Google\Chrome\User Data\Default\Extensions\cfhdojbkjhnklbpkdaibdccddilifddb\3.0.3_0 ChromeOptions options = new ChromeOptions(); options.AddArgument(@"load-extension=C:\Users\Darren\AppData\Local\Google\Chrome\User Data\Default\Extensions\cfhdojbkjhnklbpkdaibdccddilifddb\3.0.3_0"); //options.AddArgument("headless"); ChromeDriver webDriver = new ChromeDriver(options); webDriver.SwitchTo().Window(webDriver.WindowHandles[0]); webDriver.WindowHandles.Skip(1).ToList().ForEach(t => { webDriver.SwitchTo().Window(t); webDriver.Close(); }); webDriver.SwitchTo().Window(webDriver.WindowHandles[0]); webDriver.Navigate().GoToUrl(@"http://www.youtube.com"); webDriver.FindElementById("search").SendKeys(video); System.Threading.Thread.Sleep(500); webDriver.FindElementById("search-icon-legacy").Click(); System.Threading.Thread.Sleep(1500); webDriver.FindElementsById("video-title").First(v => v.Enabled && v.Displayed && v.Text.ToLower().Contains(video)).Click(); }
internal Boolean?ResponseErrorExists() { var erroMessage = driver.FindElementsById("beResponseError"); return(erroMessage.Any()); }
private IWebElement ElementSelector(ChromeDriver cDriver, string secici, int selectorType) { if (cDriver == null || string.IsNullOrWhiteSpace(secici)) { throw new ArgumentException("invalid argüment"); } ReadOnlyCollection <IWebElement> bulunan = null; switch (selectorType) { case 1: bulunan = cDriver.FindElementsByXPath(secici); break; case 2: bulunan = cDriver.FindElementsByCssSelector(secici); break; case 3: bulunan = cDriver.FindElementsById(secici); break; } return(bulunan != null && bulunan.Count > 0 ? bulunan[0] : null); }
private void LogIn(string username, string password, ChromeDriver cd) { cd.Navigate().GoToUrl("https://vk.com/feed"); List <IWebElement> webElements = (from item in cd.FindElementsById("email") where item.Displayed select item).ToList(); foreach (IWebElement element in webElements) { element.Click(); element.SendKeys(username); } webElements = (from item in cd.FindElementsById("pass") where item.Displayed select item).ToList(); foreach (IWebElement element in webElements) { element.Click(); element.SendKeys(password); } webElements = cd.FindElementsById("login_button").ToList(); webElements[0].Click(); }
private void Click_button(string name, ChromeDriver chrome) { List <IWebElement> webElements = chrome.FindElementsById(name).ToList(); if (!webElements.Any()) { return; } webElements[0].Click(); }
private void EnterData(String name, String value, ChromeDriver driver) { List <IWebElement> webElements = driver.FindElementsById(name).ToList(); if (!webElements.Any()) { return; } webElements[0].SendKeys(value); }
static void Main(string[] args) { ChromeDriver myBrowser = new ChromeDriver(); //**************************************************************************** myBrowser.Navigate().GoToUrl("http://www.hwpl.org/databases/"); myBrowser.FindElementByLinkText("ABI/INFORM Complete").Click(); myBrowser.FindElementById("barcode").SendKeys("21327001023680"); myBrowser.FindElementById("barcodeSubmit").Click(); var searchPageUrl = myBrowser.Url; myBrowser.FindElementById("searchTerm").SendKeys("(907) 225-1494"); myBrowser.FindElementById("expandedSearch").Click(); var items = myBrowser.FindElementByClassName("resultItems").FindElements(By.TagName("li")); bool found = false; foreach (var item in items) { var sourceItems = item.FindElement(By.ClassName("item")).FindElements(By.ClassName("titleAuthorETC")); foreach (var scrItem in sourceItems) { if (scrItem.Text.Contains("Experian Commercial Risk Database")) { found = true; break; } } if (found) { item.FindElement(By.TagName("h3")).FindElement(By.TagName("a")).Click(); break; } } if (!found) { myBrowser.Navigate().GoToUrl(searchPageUrl); } while (myBrowser.FindElementsById("emailLink").Count == 0) { Thread.Sleep(500); } Thread.Sleep(1000); myBrowser.FindElementById("emailLink").Click(); while (myBrowser.FindElementsByClassName("emailBccTextField").Count == 0) { Thread.Sleep(500); } Thread.Sleep(1000); myBrowser.FindElementByClassName("emailBccTextField").FindElement(By.TagName("input")).SendKeys("*****@*****.**"); myBrowser.FindElementByClassName("clsEmlUsrNm").SendKeys("Danyal"); myBrowser.FindElementByLinkText("Continue").Click(); Thread.Sleep(1000); myBrowser.Navigate().GoToUrl(searchPageUrl); }
public void CheckNotVisibleOpenForNavigator() { ChromeDriver driver = GetDriverConnection(); string url = driver.Url; ChromeDriver navigator = GetNavigatorConnection(url); ReadOnlyCollection <IWebElement> openFileInputs = navigator.FindElementsById("open-file-input"); Assert.Empty(openFileInputs); driver.Quit(); navigator.Quit(); }
public ReadOnlyCollection <IWebElement> FindElementsById(string id, int second = 10) { try { var wait = new WebDriverWait(ChromeDriver, TimeSpan.FromSeconds(second)); wait.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementIsVisible(By.Id(id))); return(ChromeDriver.FindElementsById(id)); } catch (Exception) { } return(null); }
public List <(int level, string skillClass)> GetSkillsForWorker(string workerId) { List <(int level, string skillClass)> skills = null; for (var i = 0; i < retries; i++) { try { var worker = CDriver.FindElementsById(workerId)[0]; skills = worker?.FindElements(By.CssSelector(skillsSelector)).Select(s => (level: int.Parse(s.GetAttribute("data-level")), skillClass: s.GetAttribute("class"))).ToList(); break; } catch (StaleElementReferenceException) //This happens randomly and without warning. Best solution is to try again. Odds decrease each attempt. { Thread.Sleep(10); } } return(skills); }
public void ThatKevinCanLoginAndDoStuff() { RunTest(() => { Assert.AreEqual("RideShare - Index", ChromeDriver.Title); LoginKevin(); ChromeDriver.FindElement(By.Id("addEvent")).Click(); Assert.AreEqual("RideShare - Opret en samkørsel", ChromeDriver.Title); var txtDate = ChromeDriver.FindElement(By.Id("txtDate")); txtDate.Clear(); txtDate.SendKeys(DateTime.Now.AddDays(7).ToString("yyyy-MM-dd HH:mm")); var txtDescription = ChromeDriver.FindElement(By.Id("txtDescription")); txtDescription.Clear(); txtDescription.SendKeys("Selenium test Description " + new Random().Next()); ChromeDriver.FindElement(By.Id("btnSubmit")).Click(); Assert.AreEqual("RideShare - Index", ChromeDriver.Title); ChromeDriver.FindElementsById("btnViewEvent").First().Click(); Assert.AreEqual("RideShare - Vis en samkørsel", ChromeDriver.Title); ChromeDriver.FindElementsById("btnEditEvent").First().Click(); Assert.AreEqual("RideShare - Rediger en samkørsel", ChromeDriver.Title); ChromeDriver.FindElementsById("btnCancel").First().Click(); Assert.AreEqual("RideShare - Index", ChromeDriver.Title); ChromeDriver.FindElementsById("btnViewEvent").First().Click(); Assert.AreEqual("RideShare - Vis en samkørsel", ChromeDriver.Title); ChromeDriver.FindElementsById("btnEditEvent").First().Click(); Assert.AreEqual("RideShare - Rediger en samkørsel", ChromeDriver.Title); ChromeDriver.FindElementsById("btnSubmit").First().Click(); }); }
static void Login(ChromeDriver chromeDriver) { chromeDriver.Navigate().GoToUrl("https://vk.com/feed"); Auth(chromeDriver, "email", ""); Auth(chromeDriver, "pass", ""); List <IWebElement> webElements = chromeDriver.FindElementsById("login_button").ToList(); foreach (IWebElement item in webElements) { if (!item.Displayed) { continue; } if (!item.Text.ToLower().Equals("войти")) { continue; } item.Click(); break; } }
/// <summary> /// Logs into WebReg. This will return a driver that can be used. /// </summary> /// <param name="driver">The driver.</param> /// <param name="username">The username.</param> /// <param name="password">The password.</param> /// <returns>The driver.</returns> public static async Task <ChromeDriver> Login(ChromeDriver driver, string username, string password) { driver.Navigate().GoToUrl(CapeUrl); Console.Clear(); driver.FindElementByName("urn:mace:ucsd.edu:sso:username") .SendKeys(username); driver.FindElementByName("urn:mace:ucsd.edu:sso:password") .SendKeys(password + Keys.Enter); if (driver.FindElementsById("_login_error_message").Count != 0) { ConsoleHelper.WriteLine(LogType.Error, "Your username or password was incorrect."); driver.Close(); return(null); } try { ConsoleHelper.WriteLine(LogType.Info, "Please authenticate this session with Duo 2FA. You have one " + "minute."); var wait = new WebDriverWait(driver, TimeSpan.FromMinutes(1)); wait.Until(x => x.Url.Contains("responses")); } catch (Exception) { ConsoleHelper.WriteLine(LogType.Error, "You did not authenticate with Duo 2FA in time. Please restart " + "this program."); driver.Close(); return(null); } ConsoleHelper.WriteLine(LogType.Info, "Logged in successfully."); await Task.Delay(TimeSpan.FromSeconds(3)); return(driver); }
public void LoginTest() { driver.Navigate().GoToUrl("https://localhost:44390"); driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(3); if (!driver.FindElementsById("signout").Any()) { driver.FindElementById("signupin").Click(); driver.FindElementById("email").SendKeys(email); driver.FindElementById("password").SendKeys(password); driverWait.Until(ExpectedConditions.ElementToBeClickable(By.Id("next"))).Click(); } try { driverWait.Until(ExpectedConditions.ElementIsVisible(By.Id("welcome-message"))); Assert.Contains("Hello", driver.FindElementById("welcome-message").Text); } catch { throw new XunitException(); } }
/// <summary> /// Получить элементы по Id /// </summary> /// <param name="elementId">Наименование Id</param> /// <returns>Коллекция вэб-элементов</returns> public IEnumerable <IWebElement> GetElementsById(string elementId) { return(_chromeDriver.FindElementsById(elementId)); }
private void Button_Click(object sender, RoutedEventArgs e) { List <string> titleText = JobTitle.Text.Split(' ').ToList <string>(); string jobUrlToSearch = ""; foreach (string str in titleText) { jobUrlToSearch = jobUrlToSearch + str + "-"; } jobUrlToSearch = jobUrlToSearch.Substring(0, jobUrlToSearch.Length - 1) + "-jobs/"; int i = 0; int j = 0; jobs.Add(new Job("--------------------------------- Jobs From Naukri ----------------------------")); j++; i++; var driver = new ChromeDriver(); driver.Navigate().GoToUrl("https://www.naukri.com/" + jobUrlToSearch); var urlElements = driver.FindElementsById("jdUrl"); var titles = driver.FindElementsByClassName("desig"); var locs = driver.FindElementsByClassName("loc"); foreach (var title in titles) { jobs.Add(new Job(" Job Title : " + title.GetAttribute("title"))); } foreach (var urlElement in urlElements) { jobs[i].url = urlElement.GetAttribute("href"); i = i + 1; } foreach (var loc in locs) { jobs[j].location = " \n Location : " + loc.Text; j = j + 1; } jobs.Add(new Job("--------------------------------- Jobs From Workindia ---------------------------------")); j++; i++; driver.Navigate().GoToUrl("https://www.workindia.in/software-developer-jobs-in-undefined/"); //var input = driver.FindElementByCssSelector("input[class = 'SearchInput undefined']"); //input.SendKeys("android developer"+"\n"); //WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(4)); //IWebElement autocomplete = wait.Until(x => x.FindElement(By.CssSelector("div[class = 'JobDetail LocationDetail text-secondary']"))); Thread.Sleep(20000); locs = driver.FindElementsByCssSelector("div[class = 'JobDetail LocationDetail text-secondary']"); urlElements = driver.FindElementsByClassName("JobItem"); titles = driver.FindElementsByClassName("JobItem"); foreach (var title in titles) { jobs.Add(new Job(" Job Title : " + title.FindElement(By.TagName("a")).Text)); } foreach (var urlElement in urlElements) { jobs[i].url = urlElement.FindElement(By.TagName("a")).GetAttribute("href"); i = i + 1; } foreach (var loc in locs) { jobs[j].location = " \n Location : " + loc.Text; j = j + 1; } JobsList.ItemsSource = jobs; driver.Close(); }
private static async Task Run(CliArguments args) { Console.Clear(); args.SectionIds = args.SectionIds .Where(x => x != string.Empty) .ToArray(); var chromeOptions = new ChromeOptions(); #if !DEBUG || OVERRIDE_DEBUG chromeOptions.AddArgument("--headless"); #endif chromeOptions.AddArgument("log-level=3"); var chromeService = ChromeDriverService.CreateDefaultService(AppDomain.CurrentDomain.BaseDirectory); chromeService.SuppressInitialDiagnosticInformation = true; using var driver = new ChromeDriver(chromeService, chromeOptions); #if DEBUG && !OVERRIDE_DEBUG driver.Manage().Window.Maximize(); #endif // Go to WebReg and login. driver.Navigate().GoToUrl("https://act.ucsd.edu/webreg2/start"); driver.FindElementByName("urn:mace:ucsd.edu:sso:username") .SendKeys(args.Username); driver.FindElementByName("urn:mace:ucsd.edu:sso:password") .SendKeys(args.Password + Keys.Enter); // Invalid password. if (driver.FindElementsById("_login_error_message").Any()) { Log(1, "Invalid Password. Try Again."); driver.Close(); return; } try { Log(0, "Please authenticate this session with Duo 2FA."); Wait(driver, x => x.Url.Contains("start"), TimeSpan.FromMinutes(2)); } catch (Exception) { Log(1, "Failed to authenticate. Try again."); driver.Close(); return; } Wait(driver, x => x.FindElements(By.Id("startpage-button-go")).Count != 0, TimeSpan.FromSeconds(5)); Log(0, "Logged in successfully."); // Click on "Go" driver.FindElementById("startpage-button-go").Click(); await Task.Delay(TimeSpan.FromSeconds(1)); // click on "Advanced Search" driver.FindElementById("advanced-search").Click(); var classesEnrolledIn = new List <string>(); while (true) { // Just to be nice to WebReg // Also because, occasionally, the buttons may be delayed. await Task.Delay(500); foreach (var section in args.SectionIds .Where(section => !classesEnrolledIn.Contains(section))) { // click "Reset" button driver.FindElementById("search-div-t-reset").Click(); // find the "Section ID" search box driver.FindElementById("search-div-t-t3-i4").SendKeys(section + Keys.Enter); // delay so the table can properly load // We know the table is fully loaded when the spinner is gone Wait(driver, x => x.FindElements(By.ClassName("wr-spinner-loading")).Count == 0, TimeSpan.FromSeconds(5)); // Account for minor delay. await Task.Delay(50); // check to see if there even are rows to check if (driver.FindElementsById("search-group-header-id").Count == 0) { Log(1, $"Section ID {section} not found. Is the section ID valid?"); // Check to see if we got a possible system error message // If so, close it and continue. GetPopUpElement(driver) .FirstOrDefault(x => x.GetAttribute("style").Contains("display: block;"))? .FindElements(By.Id("dialog-msg-close")) .FirstOrDefault()? .Click(); continue; } // click on the first row (there will only be one row) driver.FindElementById("search-group-header-id").Click(); // get the course dept + id var courseDeptId = driver.FindElementById("search-group-header-id") .FindElement(By.TagName("td")) .Text.Trim() // because some course dept + id has two spaces .Replace(" ", " "); // check if the enroll button exists. If it does, click. var enrollButton = driver.FindElementsById($"search-enroll-id-{section}"); if (enrollButton.Count == 0) { Log(1, $"Unable to enroll in {courseDeptId} ({section}). This class may have a wait-list " + "system."); continue; } // Make sure the button can be clicked on. if (enrollButton[0].GetAttribute("aria-disabled") == "true") { Log(1, $"Unable to enroll in {courseDeptId} ({section}). You're either enrolled in this class " + "or your enrollment time has passed."); continue; } // click on the enroll button enrollButton[0].Click(); // Wait for the popup to appear. We know the popup appears when parts of the UI is // "blocked off" due to a popup. Wait(driver, x => GetPopUpElement(x as ChromeDriver) .Any(a => a.GetAttribute("style").Contains("display: block;")), TimeSpan.FromSeconds(10)); var possiblePopups = GetPopUpElement(driver); // a popup should now appear. This is where we can attempt to confirm said enrollment. // First, check if a confirm button exists. If it doesn't, then an error occurred and we can ex var confirmButton = possiblePopups .FirstOrDefault(x => x.GetAttribute("style").Contains("display: block;"))? .FindElements(By.ClassName("ui-button-text"))? .FirstOrDefault(x => x.Text == "Confirm"); // The confirm button doesn't exist. if (confirmButton is null) { Log(1, $"Unable to enroll in {courseDeptId} ({section}). Do you have permission to " + "enroll in this course?"); var closeButton = GetPopUpElement(driver) .FirstOrDefault(x => x.GetAttribute("style").Contains("display: block;"))? .FindElements(By.Id("dialog-after-action-close")); closeButton?.FirstOrDefault()?.Click(); continue; } confirmButton.Click(); classesEnrolledIn.Add(section); Log(0, $"Successfully added section ID {section} to your schedule!"); await Task.Delay(500); var popupBox = driver.FindElementsById("dialog-after-action"); if (popupBox.Any()) { try { // TODO confirm that the button exists var emailButton = driver.FindElementById("dialog-after-action-email"); emailButton.Click(); Wait(driver, x => x.FindElements(By.Id("dialog-msg-close")).Count != 0, TimeSpan.FromSeconds(10)); var closeEmailConfirmButton = driver.FindElementById("dialog-msg-close"); closeEmailConfirmButton.Click(); Console.WriteLine("\tConfirmation Email Sent."); } catch (Exception) { try { driver.FindElementById("dialog-after-action-close").Click(); } catch (Exception) { // ignore it } } } if (classesEnrolledIn.Count >= args.MaxClassesToEnroll) { goto outLoop; } Console.WriteLine(); } } outLoop: Log(0, $"Successfully Enrolled In {classesEnrolledIn.Count} Classes."); Log(0, $"Classes: {string.Join(", ", classesEnrolledIn)}"); }
static void Main(string[] args) { try { var driverService = ChromeDriverService.CreateDefaultService(@"C:\Users\user\Desktop\pytest\chrome driver"); ChromeOptions options = new ChromeOptions(); options.AddArguments("--disable-notifications"); ChromeDriver driver = new ChromeDriver(driverService, options); //Aplikacioni që do të testojmë - YouTube driver.Url = "https://www.youtube.com/"; Thread.Sleep(3000); var Atags = driver.FindElementsByCssSelector("a[href *= 'https://accounts.google.com/ServiceLogin?']"); if (Atags.Count() != 0) { Atags.Where(c => c.Text.Contains("SIGN")).First().Click(); } //Aksesimi i llogarisë sonë var inputEmail = driver.FindElementByCssSelector("input[type='email']"); inputEmail.SendKeys("*****@*****.**"); inputEmail.SendKeys(Keys.Return); //Duhet të presim Thread.Sleep(3000); var inputPassword = driver.FindElementByCssSelector("input[type='password']"); inputPassword.SendKeys("yourpass"); inputPassword.SendKeys(Keys.Return); var spans = driver.FindElementsByTagName("span"); var donespan = spans.Where(c => c.Text.Contains("DONE")); if (donespan.Count() != 0) { //Nëse duhet verifikimi donespan.First().Click(); } Thread.Sleep(6000); //Kërkojmë për grupin Queen var search = driver.FindElementById("search"); search.Click(); search.SendKeys("Queen"); search.SendKeys(Keys.Enter); Thread.Sleep(3000); //Në rezultatet që na afishohen interesohemi për videon (këngën) Bohemian Rhapsody var videos = driver.FindElementsByTagName("h3"); var episode1 = videos.Where(c => c.Text.Contains("Bohemian Rhapsody")); if (episode1.Count() != 0) { episode1.FirstOrDefault().Click(); } //Nëse nuk e gjejmë elementin, ne e kërkojmë atë else { search.Click(); Thread.Sleep(3000); search.SendKeys(" Bohemian Rhapsody" + Keys.Enter); episode1 = driver.FindElementsByTagName("h3").Where(c => c.Text.Contains("Bohemian Rhapsody")); if (episode1.Count() != 0) { episode1.FirstOrDefault().Click(); } } //Klikojmë videon Thread.Sleep(3000); //Butoni like var likeButton = driver.FindElementByCssSelector("button[aria-label*='like']"); likeButton.Click(); //Aksesimi i elementëve të videos duke u bazuar në tastat (komandat) përkatëse //Aktivizimi/shfaqja e titrrave var cc = driver.FindElementByCssSelector("button[title='Subtitles/closed captions (c)']"); //Aktivizimi i Theater Mode var t = driver.FindElementByCssSelector("button[title='Theater mode (t)']"); t.Click(); Thread.Sleep(3000); cc.Click(); int volumedown = 0; //Ndryshimi i volumit while (volumedown <= 3) { driver.Keyboard.SendKeys(Keys.ArrowDown); volumedown++; } Thread.Sleep(3000); int seekright = 0; //Avancimi përpara në video bazuar në klikimet tona nga tastiera while (seekright <= 7) { driver.Keyboard.SendKeys(Keys.ArrowRight); seekright++; } //Play/pause bazuar në tastin 'Spacebar' driver.Keyboard.SendKeys(Keys.Space); Thread.Sleep(3000); t.Click(); Thread.Sleep(3000); //Scroll nëpërmjet tastave 'arrow' për tu pozicionuar tek komenti int counter = 0; while (counter <= 15) { driver.Keyboard.SendKeys(Keys.ArrowDown); counter++; } Thread.Sleep(3000); //Pasi pozicionohemi realizojmë komentimin var comment = driver.FindElementById("simplebox-placeholder"); comment.Click(); var box = driver.FindElementById("contenteditable-textarea"); box.SendKeys("Grupi G3 - MTS1819"); Thread.Sleep(3000); var commentButton = driver.FindElementByCssSelector("paper-button[aria-label*='Comment']"); commentButton.Click(); Thread.Sleep(5000); while (counter != 3) { driver.Keyboard.SendKeys(Keys.ArrowUp); counter--; } //Aksesojmë profilin përkatës Thread.Sleep(3000); var profile = driver.FindElementByXPath("//*[@id='owner-name']/a"); profile.Click(); Thread.Sleep(3000); //Butoni 'Subscribe' //var subscribe = driver.FindElementByCssSelector("paper-button[aria-label='Subscribe to Queen Official.']"); //subscribe.Click(); //Thread.Sleep(5000); var avatar = driver.FindElementById("avatar-btn"); avatar.Click(); Thread.Sleep(3000); //Log out var labels = driver.FindElementsById("label"); var signout = labels.Where(c => c.Text.Contains("Sign out")); if (signout.Count() != 0) { signout.First().Click(); } Thread.Sleep(3000); driver.Close(); } catch (Exception ex) { Console.WriteLine("Ndodhi një gabim. Errori:" + ex.Message); } }
public ActionResult ImportAmazonPurchases(AmazonLoginViewModel amazonLoginViewModel) { var userId = User.Identity.GetUserId(); var folderName = $@"C:\EcommerceTracker\AmazonFiles\{userId}"; var chromeOptions = new ChromeOptions(); chromeOptions.AddUserProfilePreference("download.default_directory", folderName); chromeOptions.AddUserProfilePreference("intl.accept_languages", "nl"); chromeOptions.AddUserProfilePreference("disable-popup-blocking", "true"); // Amazon uses a captcha to prevent headless browsers from logging in // chromeOptions.AddArgument("--headless"); // TODO: Move to seperate method using (var driver = new ChromeDriver(chromeOptions)) { try { // Navigate to Order History Report page driver.Navigate().GoToUrl("https://www.amazon.com/gp/b2b/reports"); // Login to Amazon, with alternate login page detection // TODO: Check if username or password are incorrect var passwordFormFieldExists = driver.FindElementsById("ap_password").Count > 0; if (passwordFormFieldExists) { driver.FindElementById("ap_email").SendKeys(amazonLoginViewModel.EmailAddress); driver.FindElementById("ap_password").SendKeys(amazonLoginViewModel.Password); driver.FindElementById("signInSubmit").Click(); } else { driver.FindElementById("ap_email").SendKeys(amazonLoginViewModel.EmailAddress); driver.FindElementById("continue").Click(); driver.FindElementById("ap_password").SendKeys(amazonLoginViewModel.Password); driver.FindElementById("signInSubmit").Click(); } var waitForForm = new WebDriverWait(driver, TimeSpan.FromSeconds(10)); waitForForm.Until(ExpectedConditions.VisibilityOfAllElementsLocatedBy(By.Id("report-form"))); // Look for existing reports // var generatedReportHistoryTableRows = driver.FindElementsByXPath("//*[@class='order-hist-submitted']/tbody/tr"); var startMonthSelect = new SelectElement(driver.FindElementById("report-month-start")); startMonthSelect.SelectByValue("1"); var startDaySelect = new SelectElement(driver.FindElementById("report-day-start")); startDaySelect.SelectByValue("1"); var startYearSelect = new SelectElement(driver.FindElementById("report-year-start")); startYearSelect.SelectByIndex(startYearSelect.Options.Count - 1); driver.FindElementById("report-use-today").Click(); driver.FindElementById("report-name").SendKeys("Generated for Ecommerce Tracker"); driver.FindElementById("report-confirm").Click(); var reportProcessed = false; var reportFailed = false; do { if (driver.FindElementsById("processing-report-table-row").Count < 1) { reportProcessed = true; } else if (driver.FindElementById("processing-long").Displayed) { driver.FindElementByXPath("//*[@id='report-refresh-button']/img").Click(); } else if (driver.FindElementById("processing-failed").Displayed) { reportFailed = true; } Thread.Sleep(TimeSpan.FromSeconds(3)); } while (!reportProcessed && !reportFailed); } catch (Exception e) { Debug.Write(e.Message); TempData["HTML"] = driver.PageSource; return(RedirectToAction("SeleniumError")); } } // TODO: Check if directory exists var fileNames = Directory.GetFiles(folderName); // TODO: Check if files exist var totalFileUploadResults = new FileUploadResultsViewModel { ExistingPurchases = _db.Purchases.Count(x => x.UserId == userId) }; var existingPurchaseFiles = _db.TrackedPurchaseFiles.Where(x => x.UserId == userId).ToList(); foreach (var fileName in fileNames) { if (existingPurchaseFiles.Select(x => x.FileName).Contains(fileName)) { continue; } var fileUploadResult = ImportAmazonFile(fileName); totalFileUploadResults.NewSites += fileUploadResult.NewSites; totalFileUploadResults.NewCategories += fileUploadResult.NewCategories; totalFileUploadResults.NewPurchases += fileUploadResult.NewPurchases; _db.TrackedPurchaseFiles.Add(new TrackedPurchaseFile { UserId = userId, FileName = fileName, FolderName = folderName, Website = "Amazon.com", ImportDate = DateTime.Now }); } _db.SaveChanges(); return(RedirectToAction("FileUploadResults", totalFileUploadResults)); }
/// <summary> /// ブラウザの制御を行う /// </summary> static void RunControlBrowser() { // ChromeDriverオブジェクトを生成します。 var chromeOptions = new ChromeOptions(); chromeOptions.Proxy = null; using (var chrome = new ChromeDriver(Environment.CurrentDirectory, chromeOptions)) { var windowHandles = new HashSet <string>(); // URLに移動します。 chrome.Url = @"http://www.google.com"; windowHandles.Add(chrome.CurrentWindowHandle); //// ページを支配下に置くための初期化、既に初期化済みの場合には処理はスキップされる //var pageInitializer = new Action<string>((handle) => { // lock (chrome) { // Console.WriteLine("----init start----"); // chrome.ExecuteScript(SetEventsJs, handle, LocalHttpServerUrl); // Console.WriteLine("----init end----"); // } //}); // ページ初期化後の処理 var knownUrls = new HashSet <string>(); PageAfterInit += new Action <JObject>(jobj => { Task.Run(() => { lock (Cmd) { Console.WriteLine("----after init start----"); var url = (string)jobj["url"]; if (!knownUrls.Contains(url)) { knownUrls.Add(url); // Google検索によるURLなら時間などの毎回変わるパラメータを除いたURLに再構築する if (url.StartsWith("https://www.google.co.jp/search") || url.StartsWith("https://www.google.com/search")) { var uri = new Uri(url); var path = uri.GetComponents(UriComponents.SchemeAndServer | UriComponents.Path, UriFormat.UriEscaped); var dic = HttpUtility.ParseQueryString(uri.Query); var list = new List <Tuple <string, string> >(); foreach (string param in dic) { switch (param) { case "q": case "oq": list.Add(new Tuple <string, string>(param, dic[param])); break; } } url = path + "?" + string.Join("&", from i in list select HttpUtility.UrlEncode(i.Item1) + "=" + HttpUtility.UrlEncode(i.Item2)); } var title = (string)jobj["title"]; var text = (string)jobj["text"]; var content = (string)jobj["content"]; var links = jobj["links"]; var searchWord = (string)jobj["searchWord"]; var urlID = Db.AddUrl(Cmd, url); Db.AddUrlTitle(Cmd, urlID, title); Db.AddUrlContent(Cmd, urlID, content); Db.AddUrlInnerText(Cmd, urlID, text); if (!string.IsNullOrEmpty(searchWord)) { Db.AddUrlSearchWord(Cmd, urlID, searchWord); } foreach (var chunk in ChunkedEnumerate(DetectKeywords(url), 1000)) { Db.AddUrlKeywords(Cmd, from kvp in chunk select new Db.TbUrlKeyword.R(urlID, Db.AddKeyword(Cmd, kvp.Key), kvp.Value)); } foreach (var chunk in ChunkedEnumerate(DetectKeywords(title), 1000)) { Db.AddTitleKeywords(Cmd, from kvp in chunk select new Db.TbTitleKeyword.R(urlID, Db.AddKeyword(Cmd, kvp.Key), kvp.Value)); } foreach (var chunk in ChunkedEnumerate(DetectKeywords(text), 1000)) { Db.AddContentKeywords(Cmd, from kvp in chunk select new Db.TbContentKeyword.R(urlID, Db.AddKeyword(Cmd, kvp.Key), kvp.Value)); } foreach (var l in links.Children <JObject>()) { var dstUrl = (string)l["h"]; var linkText = (string)l["t"]; var dstUrlID = Db.AddUrl(Cmd, dstUrl); var linkID = Db.AddLink(Cmd, urlID, dstUrlID, linkText); foreach (var chunk in ChunkedEnumerate(DetectKeywords(linkText), 1000)) { Db.AddLinkKeywords(Cmd, from kvp in chunk select new Db.TbLinkKeyword.R(linkID, Db.AddKeyword(Cmd, kvp.Key))); } } } Console.WriteLine("----after init end----"); } }); }); // ジャンプ時の処理 var knownLink = new HashSet <int>(); Jump += new Action <string, string, string, string>((src, dst, linkText, aroundText) => { Task.Run(() => { lock (Cmd) { Console.WriteLine("----jump start----"); var srcUrlID = Db.AddUrl(Cmd, src); var dstUrlID = Db.AddUrl(Cmd, dst); var linkID = Db.AddLink(Cmd, srcUrlID, dstUrlID, linkText); if (!knownLink.Contains(linkID)) { knownLink.Add(linkID); Db.AddLinkAroundText(Cmd, linkID, aroundText); foreach (var chunk in ChunkedEnumerate(DetectKeywords(aroundText), 1000)) { Db.AddLinkAroundKeywords(Cmd, from kvp in chunk select new Db.TbLinkAroundKeyword.R(linkID, Db.AddKeyword(Cmd, kvp.Key))); } Db.AddJump(Cmd, linkID); } Console.WriteLine("----jump end----"); } }); }); //// 新規ウィンドウ検出し初期化する処理 //var newWindowDetector = new Action(() => { // lock (chrome) { // var curHandles = new HashSet<string>(); // foreach (var h in chrome.WindowHandles) { // curHandles.Add(h); // } // windowHandles.RemoveWhere(h => !curHandles.Contains(h)); // foreach (var h in curHandles) { // if (!windowHandles.Contains(h)) { // windowHandles.Add(h); // chrome.SwitchTo().Window(h); // pageInitializer(chrome.CurrentWindowHandle); // } // } // } //}); //pageInitializer(chrome.CurrentWindowHandle); //// ページ終了した後のページで初期化する //Unload += new Action<string>((handle) => { // Task.Run(() => { // Console.WriteLine(chrome.Url); // pageInitializer(chrome.CurrentWindowHandle); // }); //}); //Focus += new Action<string>(handle => { //}); //// ウィンドウのフォーカスが移ったなら新しいウィンドウを探し出す //Blur += new Action<string>(handle => { // Task.Run(() => { // newWindowDetector(); // }); //}); //// ページの可視状態の切り替わりにより新しいウィンドウを探したりカレントのウィンドウを操作対象とする //VisibilityChange += new Action<string, string>((handle, visibilityState) => { // if (visibilityState == "hidden") { // Task.Run(() => { // newWindowDetector(); // }); // } else if (visibilityState == "visible") { // Task.Run(() => { // // 表示状態になったウィンドウを操作対象とする // lock (chrome) { // var curHandles = chrome.WindowHandles; // var index = curHandles.IndexOf(handle); // Console.WriteLine(index); // if (0 <= index) { // chrome.SwitchTo().Window(handle); // } // } // }); // } //}); // コマンドラインからの入力をループ ReadOnlyCollection <IWebElement> elements = null; IWebElement currentElement = null; string line; while ((line = Console.ReadLine()) != null) { if (line == "exit") { break; } else { lock (chrome) { if (int.TryParse(line, out int index)) { var wnds = chrome.WindowHandles; if ((uint)index < wnds.Count) { chrome.SwitchTo().Window(wnds[index]); } } else { var names = line.Split(' '); if (names[0].StartsWith("<")) { foreach (var e in (elements = chrome.FindElementsByXPath($"//{names[0].Substring(1)}"))) { WriteLine(e, names, 1); //js.ExecuteScript(script, e, "*****@*****.**"); } } else if (names[0] == "popup") { try { chrome.SwitchTo().Alert(); } catch (Exception ex) { Console.WriteLine(ex.Message); } } else if (names[0] == "wnds") { //foreach (var w in chrome.WindowHandles) { // chrome.SwitchTo().Window(w); // pageInitializer(w); // Console.WriteLine(w); //} } else if (names[0] == "id") { if (2 <= names.Length) { foreach (var e in (elements = chrome.FindElementsById(names[1]))) { WriteLine(e, names, 2); } } } else if (line.StartsWith("xp{")) { var(xp, atrs) = ExtractXPath(line); if (xp != null) { foreach (var e in (elements = chrome.FindElementsByXPath(xp))) { WriteLine(e, atrs, 0); } } } else if (line.StartsWith("cxp{")) { var(xp, atrs) = ExtractXPath(line); if (xp != null) { foreach (var e in (elements = currentElement.FindElements(By.XPath(xp)))) { WriteLine(e, atrs, 0); } } } else if (names[0] == "ce") { if (2 <= names.Length) { if (int.TryParse(names[1], out int elementIndex)) { if (elements != null && (uint)elementIndex < elements.Count) { WriteLine(currentElement = elements[elementIndex], names, 2); } } } } else if (names[0] == "click") { if (currentElement != null) { chrome.ExecuteScript("arguments[0].scrollIntoView(true);", currentElement); Thread.Sleep(500); currentElement.Click(); } } else if (names[0] == "setid") { Console.WriteLine(chrome.ExecuteScript(SetUniqueIdJs)); } else if (names[0] == "ready") { Console.WriteLine(chrome.ExecuteScript("return document.readyState")); } else if (names[0] == "close") { chrome.Close(); } else if (names[0] == "handle") { Console.WriteLine(chrome.CurrentWindowHandle); } else if (names[0] == "url") { Console.WriteLine(chrome.Url); } else if (names[0] == "tab") { Console.WriteLine(chrome.ExecuteScript("return document.activeElement.tabIndex")); } else if (names[0] == "js") { try { Console.WriteLine(chrome.ExecuteScript(line.Substring(2))); } catch (Exception ex) { Console.WriteLine(ex.Message); } } else if (names[0] == "init") { //pageInitializer(chrome.CurrentWindowHandle); } else if (names[0] == "s") { // s 以降のスペース区切りの文字列を and 条件で検索する // 先ず検索のキーワードを正規化 var keywords = new List <string>(); for (int i = 1; i < names.Length; i++) { foreach (var kvp in DetectKeywords(names[i])) { keywords.Add(kvp.Key); } } // キーワード分解結果表示 Console.WriteLine(string.Join(" & ", keywords)); // SQL組み立て var sql = Db.E.NewSql(); var fmain = sql.From(Db.Url); foreach (var keyword in keywords) { var a = new Argument(keyword + "%"); // キーワード指定 var fsub = sql.From(Db.Keyword); var j = fsub.InnerJoin(Db.ContentKeyword, t => t.KeywordID == fsub._.KeywordID); fsub.Where(t => Sql.Like(t.Keyword, a)); fsub.GroupBy(t => new { j._.UrlID }); fmain.InnerJoin(fsub.Select(t => new { j._.UrlID }), t => t.UrlID == fmain._.UrlID); } var jt = fmain.InnerJoin(Db.UrlTitle, t => t.UrlID == fmain._.UrlID); // 実行 var func = sql.BuildFuncFromSelect(fmain.Select(t => new { jt._.UrlTitle })); using (var reader = func.Execute(CmdForSearch)) { foreach (var r in reader.Records) { Console.WriteLine(r); } } } else if (names[0] == "l") { // l 以降のスペース区切りの文字列を and 条件で検索する // 先ず検索のキーワードを正規化 var keywords = new List <string>(); for (int i = 1; i < names.Length; i++) { foreach (var kvp in DetectKeywords(names[i])) { keywords.Add(kvp.Key); } } // キーワード分解結果表示 Console.WriteLine(string.Join(" & ", keywords)); // SQL組み立て var sql = Db.E.NewSql(); var fmain = sql.From(Db.Link); foreach (var keyword in keywords) { var a = new Argument(keyword + "%"); // キーワード指定 var fsub = sql.From(Db.Keyword); var j = fsub.InnerJoin(Db.LinkKeyword, t => t.KeywordID == fsub._.KeywordID); fsub.Where(t => Sql.Like(t.Keyword, a)); fsub.GroupBy(t => new { j._.LinkID }); fmain.InnerJoin(fsub.Select(t => new { j._.LinkID }), t => t.LinkID == fmain._.LinkID); } var jt = fmain.InnerJoin(Db.UrlTitle, t => t.UrlID == fmain._.SrcUrlID); // 実行 var func = sql.BuildFuncFromSelect(fmain.Select(t => new { jt._.UrlTitle, fmain._.LinkText })); using (var reader = func.Execute(CmdForSearch)) { foreach (var r in reader.Records) { Console.WriteLine(r); } } } } } } } // ブラウザを閉じます。 chrome.Quit(); } }
public static string RetornaRelatorios(string codigoCVM, bool buscaHistorica) { //Relatórios Financeiros using (var driver = new ChromeDriver()) { //Pegar ITR driver.Url = $"http://bvmf.bmfbovespa.com.br/cias-listadas/empresas-listadas/HistoricoFormularioReferencia.aspx?codigoCVM={codigoCVM}&tipo=itr&ano=0"; //Verificar por "Sistema Indisponível"; var linhas = new List <IWebElement>(); if (buscaHistorica) { linhas = driver.FindElementsByClassName("list-avatar-row").ToList(); } else { linhas = driver.FindElementsById("ctl00_contentPlaceHolderConteudo_rptDemonstrativo_ctl00_linha").ToList(); } foreach (var linha in linhas) { var a = linha.FindElement(By.CssSelector("a")); var nomeRelatorio = a.Text; a.Click(); driver.SwitchTo().Window(driver.WindowHandles.Last()); var select1 = driver.FindElementById("ctl00_cphPopUp_cmbGrupo"); var selectElement = new SelectElement(select1); selectElement.SelectByValue("24"); var x = driver.PageSource; driver.SwitchTo().Frame("ctl00_cphPopUp_iFrameFormulariosFilho"); var setorAtividade = driver.FindElementById("ctl00_cphPopUp_txtSetorAtividade").Text; driver.SwitchTo().DefaultContent(); select1 = driver.FindElementById("ctl00_cphPopUp_cmbGrupo"); selectElement = new SelectElement(select1); selectElement.SelectByValue("78"); var dicBalancoPatrimonial = new Dictionary <string, string>(); driver.SwitchTo().Frame("ctl00_cphPopUp_iFrameFormulariosFilho"); var tabela = driver.FindElementById("ctl00_cphPopUp_tbDados").FindElements(By.CssSelector("tr")); foreach (var item in tabela.Skip(1)) { var tds = item.FindElements(By.CssSelector("td")); var chave = tds[1].Text; var valor = tds[2].Text; if (!string.IsNullOrWhiteSpace(valor)) { dicBalancoPatrimonial.Add(chave, valor); } } } //Se for buscar tudo: //Se buscar apenas o mais novo: //Pegar DFP //http://bvmf.bmfbovespa.com.br/cias-listadas/empresas-listadas/HistoricoFormularioReferencia.aspx?codigoCVM=16284&tipo=itr&ano=0 //http://bvmf.bmfbovespa.com.br/cias-listadas/empresas-listadas/HistoricoFormularioReferencia.aspx?codigoCVM=16284&tipo=dfp&ano=0 return(""); } }