public List<FootballItem> Parse() { List<FootballItem> res = new List<FootballItem>(); IWebDriver driver = new FirefoxDriver(); driver.Navigate().GoToUrl("https://www.marathonbet.com/su/popular/Football/?menu=true#"); ReadOnlyCollection<IWebElement> main = driver.FindElements(By.ClassName("sport-category-container")); Debug.Assert(main.Count==1); ReadOnlyCollection<IWebElement> containers = main[0].FindElements(By.ClassName("category-container")); foreach (IWebElement container in containers) { ReadOnlyCollection<IWebElement> tables = container.FindElements(By.ClassName("foot-market")); Debug.Assert(tables.Count==1); ReadOnlyCollection<IWebElement> tbodys = tables[0].FindElements(By.XPath(".//tbody[@data-event-name]")); ParseTBody(tbodys, res); } /* WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10)); wait.Until((d) => { return d.Title.ToLower().StartsWith("cheese"); }); */ driver.Close(); driver.Quit(); return res; }
public void MainPage_CanSeeAllDinners_ShouldFindAFew() { using (IWebDriver driver = new FirefoxDriver()) { driver.Navigate().GoToUrl("http://www.nerddinner.com"); var searchTextDiv = (from e in driver.FindElements(By.ClassName("search-text")) where e.TagName == "div" select e).FirstOrDefault(); Assert.IsNotNull(searchTextDiv, "Should find search text which has the view all link"); var viewAllDinnerslink = searchTextDiv.FindElement(By.TagName("a")); Assert.IsNotNull(viewAllDinnerslink, "should find the view all upcoming dinners link"); viewAllDinnerslink.Click(); // now on /Dinners page var upcomingDinnersUl = (from e in driver.FindElements(By.ClassName("upcomingdinners")) where e.TagName == "ul" select e).FirstOrDefault(); Assert.IsNotNull(upcomingDinnersUl,"should find a Upcoming Dinners UL"); var dinnerLinks = upcomingDinnersUl.FindElements(By.TagName("a")); Assert.Greater(dinnerLinks.Count, 0, "There should be at least one dinner out there.. come on guys"); } }
public void SeleniumTets() { using (var driver = new FirefoxDriver(new FirefoxBinary("D:\\Program Files\\Mozilla Firefox\\firefox.exe"), new FirefoxProfile())) //using (var driver = new EdgeDriver()) { //System.Threading.Thread.Sleep(10000); driver.Manage().Window.Maximize(); driver.Navigate().GoToUrl("http://localhost:5956"); //driver.Navigate().GoToUrl("http://localhost:5956"); driver.GetScreenshot().SaveAsFile("data.png",ImageFormat.Png); driver.FindElements(By.TagName("a")).First(a => a.Text.Equals("About", StringComparison.InvariantCultureIgnoreCase)).Click(); Assert.AreEqual(driver.Url, "http://localhost:5956/Home/About"); } }
public void MainPage_CanSearchForDinners_ButNeverFindsAnyInKY() { using (IWebDriver driver = new FirefoxDriver()) { driver.Navigate().GoToUrl("http://www.nerddinner.com"); var input = driver.FindElement(By.Id("Location")); input.SendKeys("40056"); var search = driver.FindElement(By.Id("search")); search.Click(); var results = driver.FindElements(By.ClassName("dinnerItem")); // at this point, i don't know what to do, as there's never any search results. Assert.AreEqual(0, results.Count, "No dinners should be found.. omg, if this works, then its worth it to change the test"); } }
static void Main(string[] args) { IWebDriver driver = new FirefoxDriver(); StringBuilder verificationErrors = new StringBuilder(); driver.Navigate().GoToUrl("http://demo.opencart.com/"); driver.FindElement(By.XPath("(//button[@type='button'])[11]")).Click(); driver.FindElement(By.XPath("//form[@id='currency']/div/button")).Click(); driver.FindElement(By.Name("GBP")).Click(); driver.FindElement(By.Name("search")).Clear(); driver.FindElement(By.Name("search")).SendKeys("ipod"); driver.FindElement(By.XPath(".//*[@id='search']/span/button")).Click(); int NumOfElem = 0; var result = driver.FindElements(By.XPath("//*[contains(@data-original-title, 'Compare this Product')] ")); foreach (IWebElement element in result) { element.Click(); NumOfElem += 1; } driver.FindElement(By.XPath(".//*[@id='compare-total']")).Click(); for (int column = 1; column <= NumOfElem; column++) { var element = driver.FindElement(By.XPath(".//*[@id='content']/table/tbody[1]/tr[6]/td["+column+"]")).Text.ToString(); if (element == "Out Of Stock") { driver.FindElement(By.XPath(".//*[@id='content']/table/tbody[2]/tr/td[" + column + "]/a")).Click(); NumOfElem = NumOfElem - 1; column = column - 1; } } Random rnumber = new Random(); int buyproduct = rnumber.Next(2, NumOfElem + 1); var price = driver.FindElement(By.XPath(".//*[@id='content']/table/tbody[1]/tr[3]/td["+buyproduct+"]")).Text.ToString(); driver.FindElement(By.XPath(".//*[@id='content']/table/tbody[2]/tr/td[" + buyproduct + "]/input")).Click(); driver.FindElement(By.XPath("html/body/div[2]/div[1]/a[2]")).Click(); var totalprice = driver.FindElement(By.XPath(".//*[@id='content']/form/div/table/tbody/tr/td[6]")).Text.ToString(); }
static void Main(string[] args) { IWebDriver driver = new FirefoxDriver(); driver.Navigate().GoToUrl("http://www.google.com/webhp?complete=1&hl=en"); IWebElement query = driver.FindElement(By.Name("q")); query.SendKeys("Cheese"); //This line is different than the Java version above. Instead of telling the //executing thread to sleep we use an implicit wait. This means the driver won't instantly //throw an error if the suggestion box isn't there. Instead it will poll the web page until //the element is present of the timeout expires, in this case 5 seconds. driver.Manage().Timeouts().ImplicitlyWait(new TimeSpan(0, 0, 5)); ReadOnlyCollection<IWebElement> allSuggestions = driver.FindElements(By.XPath("//td[@class='gac_c']")); foreach (IWebElement suggestion in allSuggestions) { System.Console.WriteLine(suggestion.Text); } System.Console.ReadLine(); driver.Quit(); }
public void Should_display_10_items_per_page_select_by_XPath() { IWebDriver driver = new FirefoxDriver(); driver.Navigate().GoToUrl("http://localhost:1392/"); driver.FindElement(By.Id("login_UserName")).Clear(); driver.FindElement(By.Id("login_UserName")).SendKeys("Admin"); driver.FindElement(By.Id("login_Password")).Clear(); driver.FindElement(By.Id("login_Password")).SendKeys("testing"); driver.FindElement(By.Id("login_LoginButton")).Click(); driver.FindElement(By.LinkText("Orders")).Click(); var rows = driver.FindElements(By.XPath("//table/tbody/tr")); Assert.AreEqual(12, rows.Count); driver.FindElement(By.Id("LoginStatus1")).Click(); driver.Quit(); }
public void CheckNavBar_GetElements() { _output.WriteLine("Step 00 : 准备测试数据。"); var testDatas = new List<string>() { "首页", "精华", "候选", "新闻" }; //准备测试数据 _output.WriteLine("Step 01 : 启动浏览器并打开博客园首页。"); IWebDriver driver = new FirefoxDriver(); driver.Url = "http://www.cnblogs.com"; _output.WriteLine("Step 02 : 寻找需要检查的页面元素。"); var divMain = driver.FindElement(By.Id("main")); var lnkNavList = driver.FindElements(By.XPath(".//ul[@class='post_nav_block']/li[1]/a")); _output.WriteLine("Step 03 : 检查导航条文字信息。"); for (var i = 0; i < lnkNavList.Count; i++) { Assert.Equal<string>(testDatas[i], lnkNavList[i].Text); } _output.WriteLine("Step 04 : 关闭浏览器。"); driver.Close(); }
public void GoToCoord() { IWebDriver driver = new FirefoxDriver(); TransformJS js = new TransformJS(driver); Login login = new Login(driver); login.get().login("guest", "guest").click();//вход на сайт LonLat startPoint = js.getMapCenter();//находим центр GoToCoordWnd(driver);// ищем по заданным координатам IList<IWebElement> img = driver.FindElements(By.ClassName("olAlphaImg"));//находим указатель int x = img[0].Location.X + img[0].Size.Width / 2; //ищем координаты картинки по x int y = img[0].Location.Y - img[0].Size.Height / 3; // ищем координаты картинки по y string Latimg1 = js.getLonLatFromPixel(x, y);//переводим экранные координаты LonLat imgCoord = new LonLat(Latimg1);// находи lon и lat кaртинки в неправильном формате string imgPoint = js.transferFrom(imgCoord.getLon(), imgCoord.getLat(), 900913, 4326);//находим правильный lon и lat LonLat coord5 = new LonLat(imgPoint); double imgLon = coord5.getLon(); //находи lon кaртинки double imgLat = coord5.getLat();//находи lat кaртинки LonLat changedPoint = js.getMapCenter(); // вычисляем координаты изменившегося центра. Получаем:"lon=69.9833333333329,lat=60.84722222222229" if (LonLat.equalLonLat(changedPoint, startPoint)==false)//сравниваем начальные значения центра с изменившимися координатами заданными нами { Assert.Fail("центр не изменен"); } double changedLon = changedPoint.getLon();//находим lon получившегося цента double changedLat = changedPoint.getLat();//находим lat получившегося цента double specLon1= getDecimalDegree(69, 59, 0);// находим lon введенный нами double specLat1 = getDecimalDegree(60, 50, 50);//находим lat введенный нами if (changedLon != specLon1 || changedLat != specLat1)//сравниваем начальные значения центра с изменившимися координатами заданными нами { Assert.Fail("не правильный переход"); } // проверяем находится ли указатель в координатах заданными нами if (imgLon != specLon1 || imgLat != specLat1)//сравниваем начальные значения центра с изменившимися координатами заданными нами { Assert.Fail("не правильный переход"); } }
//check for login public static Boolean checkForLogin(FirefoxDriver driver) { if (driver.FindElements (By.Id ("email")) > 0) return true; return false; }
protected void Button4_Click(object sender, EventArgs e) { // Response.Write(marker_place); List<string> lst_zipscodes = new List<string>(); IGeocoder geocoder = new GoogleGeocoder() { }; DataSet ds = new DataSet("Sites_Collection"); string connection_string = ConfigurationManager.ConnectionStrings["UA_NAVConnectionString"].ConnectionString; SqlConnection conn = new SqlConnection(connection_string); WeatherReference.WeatherSoapClient weather = new WeatherReference.WeatherSoapClient("WeatherSoap"); // my source starting placeplace for (int i = 0; i < marker_place.Count; i++) { string source = marker_place[i]; string[] addr_string = source.Split(','); string[] zipcode = null; if (addr_string.Count() == 4) { zipcode = addr_string[2].Trim().Split(' '); source = addr_string[1] + "," + zipcode[0]; lst_zipscodes.Add(zipcode[1]); } else { continue; } IWebDriver driver = null; try { driver = new FirefoxDriver(); driver.Navigate().GoToUrl("http://www.nwf.org/naturefind.aspx"); driver.Manage().Window.Maximize(); var place_name = driver.FindElement(By.Id("content_0_txtBasicSearch")); place_name.Clear(); place_name.SendKeys(source); driver.FindElement(By.Id("content_0_btnSearchSites")).Click(); //driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(10)); IWait<IWebDriver> wait = new OpenQA.Selenium.Support.UI.WebDriverWait(driver, TimeSpan.FromSeconds(15.00)); // IWait<IWebDriver> wait = null; wait.Until(driver1 => ((IJavaScriptExecutor)driver).ExecuteScript("return document.readyState").Equals("complete")); DataTable dt = new DataTable("Places_" + i); DataColumn place_Coulumn = new DataColumn("Scenic_Place_Name", Type.GetType("System.String")); DataColumn lat_Coulumn = new DataColumn("Latitude", Type.GetType("System.String")); DataColumn lng_Coulumn = new DataColumn("Longitude", Type.GetType("System.String")); DataColumn address_of_place = new DataColumn("Address", Type.GetType("System.String")); DataColumn Zipscode = new DataColumn("Zipcode", Type.GetType("System.String")); DataColumn weather_desc = new DataColumn("Weather", Type.GetType("System.String")); DataColumn temperature = new DataColumn("Temperature", Type.GetType("System.String")); DataColumn traffic = new DataColumn("Traffic", Type.GetType("System.String")); DataColumn safety = new DataColumn("Safety", Type.GetType("System.String")); dt.Columns.Add(place_Coulumn); dt.Columns.Add(lat_Coulumn); dt.Columns.Add(lng_Coulumn); dt.Columns.Add(address_of_place); dt.Columns.Add(Zipscode); dt.Columns.Add(weather_desc); dt.Columns.Add(temperature); dt.Columns.Add(traffic); dt.Columns.Add(safety); DataRow dr; int count1 = 0; try { wait.Until(ExpectedConditions.ElementIsVisible(By.XPath("//div[@id='content_0_grdSiteList']//tr[@class='rgRow']//u"))); wait.Until(ExpectedConditions.ElementExists(By.XPath("//div[@id='content_0_grdSiteList']//tr[@class='rgRow']//u"))); IList<IWebElement> lst_places = driver.FindElements(By.XPath(".//div[@id='content_0_grdSiteList']//tr[@class='rgRow']//u")); if (lst_places == null) continue; int count = 0; foreach (IWebElement place in lst_places) { // if (count1!= -1) // { try { dr = dt.NewRow(); Thread.Sleep(200); dr["Scenic_Place_Name"] = place.Text; IEnumerable<Address> addresses = geocoder.Geocode(place.Text + "," + zipcode[0]); string place_addr = null; Location ltng = null; foreach (Address adr in addresses) { if (count == 0) { place_addr = adr.FormattedAddress; ltng = adr.Coordinates; dr["Address"] = place_addr; break; } } dr["Latitude"] = ltng.Latitude; dr["Longitude"] = ltng.Longitude; //tokenize place address string[] array = place_addr.Split(','); string[] waypoints = place_addr.Split(','); ///////******************* string zip = array[array.Length - 2]; string[] arr = zip.Trim().Split(' '); string webservicezip = null; if (arr.Length == 1) { dr["Zipcode"] = zipcode[1]; webservicezip = zipcode[1]; } else if (Regex.IsMatch(place_addr, @"\d")) { arr = zip.Trim().Split(' '); dr["Zipcode"] = arr[1].Trim(); webservicezip = arr[1].Trim(); } //weather update WeatherReference.WeatherReturn weather_of_place = weather.GetCityWeatherByZIP(webservicezip); // arr[1].Trim() dr["Weather"] = weather_of_place.Description; dr["Temperature"] = weather_of_place.Temperature; Random rnd = new Random(); dr["Traffic"] = rnd.Next(2, 5); dr["Safety"] = rnd.Next(60, 100); dt.Rows.Add(dr); //break; } catch (Exception ex) { Console.WriteLine(ex); continue; } } } finally { ds.Tables.Add(dt); } } finally { driver.Close(); driver.Dispose(); } } WriteDataToDATABASE(ds); string[] scenic_places = CreateListScenicPlaces(); // DrawScenicDirection(); foreach (string s in scenic_places) { ClientScript.RegisterArrayDeclaration("scenic_places", "\"" + s + "\""); } ClientScript.RegisterStartupScript(Page.GetType(), "Scenic", "scenic_route();", true); }
static void Main(string[] args) { IWebDriver driver = new FirefoxDriver(); StringBuilder verificationErrors = new StringBuilder(); driver.Navigate().GoToUrl("http://demo.opencart.com/"); //ad.1 the command above opens browser and required page driver.FindElement(By.XPath("(//button[@type='button'])[11]")).Click(); //probably the command above should be removed, but I can not verify it now (the website is offline) driver.FindElement(By.XPath("//form[@id='currency']/div/button")).Click(); driver.FindElement(By.Name("GBP")).Click(); //ad.2 currency is changed to GBP now driver.FindElement(By.Name("search")).Clear(); driver.FindElement(By.Name("search")).SendKeys("iPod"); driver.FindElement(By.XPath(".//*[@id='search']/span/button")).Click(); //ad.3 program is looking for items which contains "iPod" in title int NumOfElem = 0; var result = driver.FindElements(By.XPath("//*[contains(@data-original-title, 'Compare this Product')] ")); foreach (IWebElement element in result) { element.Click(); NumOfElem += 1; } //ad.4 the function adds all iPods returned in search results to product comparison driver.FindElement(By.XPath(".//*[@id='compare-total']")).Click(); //ad.5 the command above opens product comparison page for (int column = 1; column <= NumOfElem; column++) { var element = driver.FindElement(By.XPath(".//*[@id='content']/table/tbody[1]/tr[6]/td[" + column + "]")).Text.ToString(); if (element == "Out Of Stock") { driver.FindElement(By.XPath(".//*[@id='content']/table/tbody[2]/tr/td[" + column + "]/a")).Click(); NumOfElem = NumOfElem - 1; column = column - 1; } } //ad.6 Because I know that the text "out of string" is always in table row number 6, I am looking for td number which contains it. //The loop is looking for "out of stock" text, if finds, puts the "td number" into variable and clicks the "remove" button in the same table column Random rnumber = new Random(); int buyproduct = rnumber.Next(2, NumOfElem + 1); var price = driver.FindElement(By.XPath(".//*[@id='content']/table/tbody[1]/tr[3]/td[" + buyproduct + "]")).Text.ToString(); // take the product price and puts it into variable driver.FindElement(By.XPath(".//*[@id='content']/table/tbody[2]/tr/td[" + buyproduct + "]/input")).Click(); //ad.7 Adds a random avaible iPod to shopping cart driver.FindElement(By.XPath("html/body/div[2]/div[1]/a[2]")).Click(); // while executing this command the shopping cart should be opened, unfortunatelly xPath doesn't work correctly (can not change - website offline) var totalprice = driver.FindElement(By.XPath(".//*[@id='content']/form/div/table/tbody/tr/td[6]")).Text.ToString(); if (string.Equals(price, totalprice)) { Console.WriteLine("Everything is OK, the product price is same as total price"); Console.ReadKey(); } else { Console.WriteLine("There is something wrong! Total price is different than the price of your product!"); Console.ReadKey(); } // here program compares two variables ("price" and "totalprice" if they are equal or not }