Advertisement
andruhovski

Day 02

Nov 10th, 2018
235
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.78 KB | None | 0 0
  1. using Aspose.Html;
  2. using System;
  3. using System.Collections.Concurrent;
  4. using System.Linq;
  5. using System.Threading;
  6.  
  7. namespace Day02
  8. {
  9.     class Program
  10.     {
  11.         static void Main(string[] args)
  12.         {          
  13.             var cities = new ConcurrentBag<City>();
  14.             var wait = new ManualResetEvent(false);
  15.  
  16.             Console.WriteLine("Started");
  17.             // Parse for html doc
  18.             var htmlDocument = new HTMLDocument();
  19.             htmlDocument.OnLoad += (sender, e) =>
  20.             {
  21.                 var doc = (HTMLDocument)sender;
  22.                 var htmlTables = htmlDocument.DocumentElement.GetElementsByTagName("table");
  23.                 if (htmlTables.Count() > 0)
  24.                 {
  25.                     var rows = htmlTables[0].GetElementsByTagName("tr");
  26.                     for (int i = 1; i < rows.Length; i++)
  27.                     {
  28.                         var cells = rows[i].GetElementsByTagName("td");
  29.                         var city = new City
  30.                         {
  31.                             Rank = Convert.ToInt32(cells[0].TextContent),
  32.                             CityName = cells[1].TextContent,
  33.                             Country = cells[2].TextContent,
  34.                             Popuplation = Convert.ToDouble(cells[3].TextContent.Replace(",", ""))
  35.                         };
  36.                         cities.Add(city);
  37.                     }
  38.                     wait.Set();
  39.                 };
  40.             };
  41.             htmlDocument.Navigate("https://www.worldatlas.com/citypops.htm");          
  42.             wait.WaitOne();        
  43.             foreach (var city in cities)
  44.             {
  45.                 Console.WriteLine($"{city.Rank} {city.CityName} {city.Country} {city.Popuplation}");
  46.             }
  47.         }
  48.     }
  49. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement