/// <summary> /// Парсит html страницы яндекс погоды /// </summary> private async void DoWork(object obj) { _logger.LogInformation("Получение всех городов."); TownWeatherContext townWeatherContext = new TownWeatherContext(); WebRequest webRequest = WebRequest.Create(Domen + Region); webRequest.Method = "GET"; WebResponse response = await webRequest.GetResponseAsync(); using (StreamReader reader = new StreamReader(response.GetResponseStream())) { //Парсим html string html = reader.ReadToEnd(); HtmlParser parser = new HtmlParser(); IHtmlDocument document = parser.ParseDocument(html); foreach (IElement element in document.QuerySelectorAll(".place-list__item-name")) { string townName = element.InnerHtml; //Если город уже есть в бд, то не добавляем его, а обновляем ему погоду. Town town = townWeatherContext .Towns .Where(t => t.Name == townName) .Include(t => t.Weathers) .FirstOrDefault(); if (town == null) { town = new Town { Name = townName, Weathers = new List <Weather>() }; SetWeathers(element.GetAttribute("href"), town); townWeatherContext.Towns.Add(town); } else { town.Weathers.Clear(); townWeatherContext.SaveChanges(); SetWeathers(element.GetAttribute("href"), town); } townWeatherContext.SaveChanges(); } } response.Close(); }
public TownsController(ILogger <TownsController> logger) { _logger = logger; _context = new TownWeatherContext(); }