In the below WeatherScraper class I have a getdata function to gather the data that has…
- User
In the below WeatherScraper class I have a get_data function to gather the data that has been scraped. In the db_operations class I have an update_weather_data function that should update the database with the missing data from the last date in the database up to and including the current day. The get_data function however naturally iterates from the most recent date until the earliest date, so how would I use get_data in this context?
''' A module that encapsulates a web scraper. This module scrapes data from a website. ''' from html.parser import HTMLParser import urllib.request from datetime import datetime, timedelta import logging from dateutil.parser import parse
class WeatherScraper(HTMLParser): """A parser for extracting temperature values from a website."""
logger = logging.getLogger("main." + __name__) def __init__(self): try: super().__init__() self.is_tbody = False self.is_td = False self.is_tr = False self.last_page = False self.counter = 0 self.daily_temps = {} self.weather = {} self.row_date = "" self.initial_date = None except Exception as error: self.logger.error("scrape:init:%s", error) def is_valid_date(self, date_str): """Check if a given string is a valid date.""" try: parse(date_str, default=datetime(1900, 1, 1)) return True except ValueError: return False def is_numeric(self, temp_str): """Check if given temperature string can be converted to a float.""" try: float(temp_str) return True except ValueError: return False def handle_starttag(self, tag, attrs): """Handle the opening tags.""" try: if tag == "tbody": self.is_tbody = True if tag == "tr" and self.is_tbody: self.is_tr = True if tag == "td" and self.is_tr: self.counter += 1 self.is_td = True # Only parses the valid dates, all other values are excluded. if tag == "abbr" and self.is_tr and self.is_valid_date(attrs[0][1]): self.row_date = str(datetime.strptime(attrs[0][1], "%B %d, %Y").date()) # if len(attrs) == 2: # if attrs[1][1] == "previous disabled": # self.last_page = True except Exception as error: self.logger.error("scrape:starttag:%s", error) def handle_endtag(self, tag): """Handle the closing tags.""" try: if tag == "td": self.is_td = False if tag == "tr": self.counter = 0 self.is_tr = False except Exception as error: self.logger.error("scrape:end:%s", error) def handle_data(self, data): """Handle the data inside the tags.""" if data.startswith("Daily Data Report for January 2023"): self.last_page = True try: if self.is_tbody and self.is_td and self.counter <= 3 and data.strip(): if self.counter == 1 and self.is_numeric(data.strip()): self.daily_temps["Max"] = float(data.strip()) if self.counter == 2 and self.is_numeric(data.strip()): self.daily_temps["Min"] = float(data.strip()) if self.counter == 3 and self.is_numeric(data.strip()): self.daily_temps["Mean"] = float(data.strip()) self.weather[self.row_date] = self.daily_temps self.daily_temps = {} except Exception as error: self.logger.error("scrape:data:%s", error) def get_data(self): """Fetch the weather data and return it as a dictionary of dictionaries.""" current_date = datetime.now() while not self.last_page: try: url = f"https://climate.weather.gc.ca/climate_data/daily_data_e.html?StationID=27174&timeframe=2&StartYear=1840&EndYear=2018&Day={current_date.day}&Year={current_date.year}&Month={current_date.month}" with urllib.request.urlopen(url) as response: html = response.read().decode() self.feed(html) # Subtracts one day from the current date and assigns the # resulting date back to the current_date variable. current_date -= timedelta(days=1) except Exception as error: self.logger.error("scrape:get_data:%s", error) return self.weather - Assistant
To use the
get_datafunction in the context of updating the database with missing data, you can modify the function to accept astart_dateparameter, which will be the date from which you want to start scraping the data. Then, instead of initializing the variable to , you can initialize it to the . This way, the function will start scraping data from the specified date until the earliest date. - User
- Assistant
Based on your code, the
get_datamethod keeps running past the last date in the database because there is no condition to check whether thecurrent_dateis equal to or older than the last date in the database.To fix this issue, you can add a condition in the while loop in the
get_datamethod to make it stop when it reaches the last date in the database:def get_data(self, initial_date = None): """Fetch the weather data and return it as a dictionary of dictionaries.""" if initial_date is None: current_date = datetime.now().date() else: current_date = initial_date if self.initial_date is not None: end_date = self.initial_date - timedelta(days=1) else: end_date = None while not self.last_page: if end_date and current_date <= end_date: break try: url = f"https://climate.weather.gc.ca/climate_data/daily_data_e.html?StationID=27174&timeframe=2&StartYear=1840&EndYear=2018&Day={current_date.day}&Year={current_date.year}&Month={current_date.month}" with urllib.request.urlopen(url) as response: html = response.read().decode() self.feed(html) # Subtracts one day from the current date and assigns the # resulting date back to the current_date variable. current_date -= timedelta(days=1) print(url) except Exception as error: self.logger.error("scrape:get_data:%s", error) return self.weather - User
Get_data STARTS at the end date, and should iterate to the current date in that case. If there isn't any previous data then it should start at the current date and iterate as far back as possible.
- Assistant
I see, in that case, you can modify the
get_datamethod as follows:- Add an optional argument
end_dateto the method, which will be the date until which the method should scrape the data. - Replace the
if end_date and current_date <= end_date:condition withif end_date and current_date >= end_date:to make sure the method keeps running until it reaches the specified end date or when there is no more data to scrape.
Here's the updated method:
- Add an optional argument