andruhovski icon

Day 02

andruhovski | PRO | 11/10/18 01:25:46 PM UTC | 0 ⭐ | 634 👁️ | Never ⏰ | []
C# |

1.78 KB

|

None

|

0 👍

/

0 👎

using Aspose.Html;
using System;
using System.Collections.Concurrent;
using System.Linq;
using System.Threading;
 
namespace Day02
{
    class Program
    {
        static void Main(string[] args)
        {           
            var cities = new ConcurrentBag<City>();
            var wait = new ManualResetEvent(false);
 
            Console.WriteLine("Started");
            // Parse for html doc
            var htmlDocument = new HTMLDocument();
            htmlDocument.OnLoad += (sender, e) =>
            {
                var doc = (HTMLDocument)sender;
                var htmlTables = htmlDocument.DocumentElement.GetElementsByTagName("table");
                if (htmlTables.Count() > 0)
                {
                    var rows = htmlTables[0].GetElementsByTagName("tr");
                    for (int i = 1; i < rows.Length; i++)
                    {
                        var cells = rows[i].GetElementsByTagName("td");
                        var city = new City
                        {
                            Rank = Convert.ToInt32(cells[0].TextContent),
                            CityName = cells[1].TextContent,
                            Country = cells[2].TextContent,
                            Popuplation = Convert.ToDouble(cells[3].TextContent.Replace(",", ""))
                        };
                        cities.Add(city);
                    }
                    wait.Set();
                };
            };
            htmlDocument.Navigate("https://www.worldatlas.com/citypops.htm");           
            wait.WaitOne();         
            foreach (var city in cities)
            {
                Console.WriteLine($"{city.Rank} {city.CityName} {city.Country} {city.Popuplation}");
            }
        }
    }
}

Comments