''' A module that encapsulates a web scraper. This module scrapes data from a website.…
- User
''' 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 = "" 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, 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 initial_date is not None: end_date = 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) except Exception as error: self.logger.error("scrape:get_data:%s", error) return self.weather - Assistant
This script consists of two parts:
- A
WeatherScraperclass that scrapes weather data from a website and stores it in a dictionary. - A
DBOperationsclass that interacts with a SQLite database to store, update, and retrieve weather data.
The
WeatherScraperclass uses theHTMLParserlibrary to parse weather data from the website. It reads through the HTML content of the website and stores relevant weather data, such as minimum, maximum, and mean temperature, in a dictionary with the date as the key.The
DBOperationsclass manages a SQLite database with a table for storing weather data. It provides methods for initializing, saving, fetching, updating, and purging data from the database.Some example tasks you could accomplish using this script include:
- Scrape weather data from a specific date range and save it to a SQLite database.
- Retrieve weather data for a particular location from the SQLite database.
- Update the weather data in the SQLite database by fetching new data from the website.
- Purge all weather data from the SQLite database.
- A
- User
I'm having an issue with updating weather. The get_data function currently adds data from the current date and goes as far back as possible. For updating, I'm assuming that there is already preexisting data in the database. If the most recent date in the database is BEFORE the current date, I need to run get_data but only until it reaches the most recent date in the database since iterating anything past that will be useless and risk having duplicate data.
- Assistant
You can modify the
get_datamethod of theWeatherScraperclass to take an additional argumentend_date. This will be the last date for which data is needed. Then, you can update the loop condition to check whether the is equal to or less than the . - User
I'm getting this error: while not self.last_page and end_date is None or current_date > end_date: ^^^^^^^^^^^^^^^^^^^^^^^ TypeError: '>' not supported between instances of 'datetime.date' and 'NoneType'
- Assistant
Apologies for the confusion, I made an error in the while loop condition. To fix this issue, you can simply update the while loop condition by using parentheses for different checks. Here's the corrected while loop condition in the
get_datamethod of theWeatherScraperclass:while not self.last_page and (end_date is None or current_date > end_date):With this change, the while loop will first evaluate if
self.last_pageis False and then check if eitherend_dateis None orcurrent_date > end_date. This should resolve the error you were facing.