'''
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."""
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."""
if self.initial_date is None:
current_date = datetime.now()
else:
current_date = self.initial_date
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
The code provided includes four classes:
WeatherScraper: This class scrapes weather data, such as max temperature, min temperature, and mean temperature, from a specified website, and returns the weather data in a dictionary format.
DBOperations: This class deals with database operations, such as initializing the database, saving data to the database, fetching data from the database, purging data from the database, and getting a cursor for database operations.
DBCM: This class represents a connection to a database and is used as a context manager to automatically handle committing or rolling back changes and closing the connection after the completion of the context.
WeatherProcessor: This class brings together the functionality of the WeatherScraper, DBOperations, and PlotOperations classes to download or update weather data, save the data to a database, and generate box and line plots based on user input.
User
The update portion should be following these requirements, but for some reason its not working. Any idea why?
When updating, the program should check today’s date and the latest
date of weather available in the DB, and download what’s missing
between those two points, without duplicating any data.
Assistant
The issue with the update_weather_data function in the WeatherProcessor class is that it does not properly handle the period between the latest date in the database and today's date for fetching missing data. Here's an updated version of the update_weather_data function that should work as expected:
def update_weather_data(self):
# Get the latest entry from the database
latest_date_in_db = self.db_operations.get_latest_date_in_db()
if latest_date_in_db:
# If there is a latest entry, get its date
latest_date_in_db = datetime.strptime(latest_date_in_db, '%Y-%m-%d').date()
today_date = datetime.now().date()
# Calculate the difference between the latest date in the database and the current date
days_difference = (today_date - latest_date_in_db).days
# Compare the latest date to the current date
if days_difference > 0:
# Set the initial_date attribute of the WeatherScraper instance to the latest date in the database
self.scrape_weather.initial_date = latest_date_in_db
# Scrape the missing weather data between the latest date in the database and today's date
data = self.scrape_weather.get_data()
# Save the missing weather data to the database
self.db_operations.save_data(data)
else:
# If there is no latest entry, fetch the weather data
data = self.scrape_weather.get_data()
# Save the weather data to the database
self.db_operations.save_data(data)
User
Would it better to move that function to db operations
Assistant
Yes, moving the update_weather_data function to the DBOperations class can be a better design choice as it would keep all the database-related operations in one class. Here's an example of how you could modify the DBOperations class to include the update_weather_data function:
class DBOperations:
...
def update_weather_data(self, weather_scraper):
# Get the latest entry from the database
latest_date_in_db = self.get_latest_date_in_db()
if latest_date_in_db:
# If there is a latest entry, get its date
latest_date_in_db = datetime.strptime(latest_date_in_db, '%Y-%m-%d').date()
today_date = datetime.now().date()
# Calculate the difference between the latest date in the database and the current date
days_difference = (today_date - latest_date_in_db).days
# Compare the latest date to the current date
if days_difference > 0:
# Set the initial_date attribute of the WeatherScraper instance to the latest date in the database
weather_scraper.initial_date = latest_date_in_db
# Scrape the missing weather data between the latest date in the database and today's date
data = weather_scraper.get_data()
# Save the missing weather data to the database
self.save_data(data)
else:
# If there is no latest entry, fetch the weather data
data = weather_scraper.get_data()
# Save the weather data to the database
self.save_data(data)
User
How do I access initial date?
Assistant
To access the initial_date attribute of the WeatherScraper class, you can use the instance variable of the WeatherScraper object. Here's an example:
# Create an instance of WeatherScraper
scraper = WeatherScraper()
# Set the initial_date attribute for the instance
scraper.initial_date = datetime(2022, 1, 1).date()
# Access the initial_date attribute of the instance
initial_date = scraper.initial_date
print("Initial Date:", initial_date)
In the context of the WeatherProcessor class, you can access or modify the initial_date attribute of the scrape_weather instance like this:
class WeatherProcessor:
...
def some_function(self):
# Set the initial_date attribute for the scrape_weather instance
self.scrape_weather.initial_date = datetime(2022, 1, 1).date()
# Access the initial_date attribute of the scrape_weather instance
initial_date = self.scrape_weather.initial_date
print("Initial Date:", initial_date)
You can replace the some_function method with any desired method in the WeatherProcessor class where you need to access or modify the .
User
Do I have to change anything in weatherscraper to access this attribute?
Assistant
In the existing code, the initial_date attribute is not explicitly defined by default in the WeatherScraper class. To better handle the attribute, you can define it in the __init__() method of the class and assign a default value of None.
Here's an updated version of the WeatherScraper class with an explicitly defined initial_date attribute:
class WeatherScraper(HTMLParser):
...
def __init__(self):
try:
super().__init__()
...
self.initial_date = None
except Exception as error:
self.logger.error("scrape:init:%s", error)
...
With this modification, you can access and modify the initial_date attribute directly using an instance of the WeatherScraper class, as shown in the previous examples. There are no other changes needed in the WeatherScraper class to access this attribute.
User
Why am I not able to access the initial_date here? Or am I?
Assistant
My apologies for the confusion in the previous response. After reviewing the code again, I realized the initial_date attribute is already properly initialized in the WeatherScraper class. You can access initial_date in other classes using the instance of the WeatherScraper class without any issues.
In the provided code, in the WeatherProcessor class (or any other class), you can access the initial_date attribute from the scrape_weather instance as follows:
class WeatherProcessor:
...
def some_function(self):
# Access the initial_date attribute of the scrape_weather instance
initial_date = self.scrape_weather.initial_date
print("Initial Date:", initial_date)
Replace some_function with the desired method in the WeatherProcessor class where you want to access the initial_date.
There is no need to make any changes to the WeatherScraper class. You can access the initial_date attribute as shown in the example code above.
User
The get_data function iterates from the current day backwards, but in this context I want to get the data missing from the last date in the db, to the current date.
Assistant
In order to change the direction of the iteration for the function in the class, you can follow these steps:
User
Does this also work if there isn't already data in the database and I need to gather ALL the data?
Assistant
Yes, the updated WeatherScraper class with the changes I provided in the previous response can handle both cases when there is already data in the database (for updating) and when there is no data (for gathering all the data).
When the database is empty, and you want to gather all the data, the update_weather_data() function in the DBOperations class will handle this case in the else block:
class DBOperations:
...
def update_weather_data(self, weather_scraper):
...
else:
# If there is no latest entry, fetch the weather data
data = weather_scraper.get_data()
# Save the weather data to the database
self.save_data(data)
...
In this case, the initial_date and end_date attributes are both None by default, and the get_data() function in the class will start gathering data from the current date and continue backwards in time (since it can't find an ending date).
Test program.
if name == "main":
print_data = WeatherScraper().get_data()
for k, v in print_data.items():
print(k, v)
'''
A Module that creates and modifies a database. In this case, the data is weather information
scraped from a webpage.
'''
import sqlite3
import logging
from dateutil import parser
from scrape_weather import WeatherScraper
class DBOperations:
"""Class for performing operations on a SQLite database"""
def __init__(self, dbname):
"""
Constructor for DBOperations class.
Parameters:
- dbname: str, the name of the SQLite database file to use
"""
self.dbname = dbname
self.logger = logging.getLogger(__name__)
def initialize_db(self):
"""
Initialize the SQLite database by creating the weather_data table.
This method should be called every time the program runs.
"""
with self.get_cursor() as cursor:
try:
cursor.execute('''
CREATE TABLE IF NOT EXISTS weather_data (
id INTEGER PRIMARY KEY AUTOINCREMENT,
sample_date TEXT UNIQUE,
location TEXT,
min_temp REAL,
max_temp REAL,
avg_temp REAL
)
''')
self.logger.info("Initialized database successfully.")
except sqlite3.Error as error:
self.logger.error("An error occurred while creating the table: %s", error)
def save_data(self, data):
"""
Save weather data to the SQLite database.
If the data already exists in the database, it will not be duplicated.
Parameters:
- data: dict, the weather data to save to the database. Must have keys for
sample_date, location, min_temp, max_temp, and avg_temp.
"""
# Initialize the database
data_base = DBOperations("../mydatabase.db")
data_base.initialize_db()
# Process the data and prepare the rows
rows = []
for date, temps in data.items():
row = (
date,
"Winnipeg",
temps["Max"],
temps["Min"],
temps["Mean"]
)
rows.append(row)
# Save the data to the database
with data_base.get_cursor() as cursor:
try:
cursor.executemany('''
INSERT OR IGNORE INTO weather_data
(sample_date, location, min_temp, max_temp, avg_temp)
VALUES (?, ?, ?, ?, ?)
''', rows)
data_base.logger.info("Inserted %s rows into the database.", len(rows))
except sqlite3.Error as error:
data_base.logger.error("An error occurred while inserting data: %s", error)
def fetch_data(self, location):
"""
Fetch weather data from the SQLite database for a specified location.
Parameters:
- location: str, the location to fetch weather data for
Returns:
- A list of tuples containing the weather data for the specified location,
where each tuple has the format (sample_date, min_temp, max_temp, avg_temp).
Returns an empty list if no data is found for the specified location.
"""
with self.get_cursor() as cursor:
try:
cursor.execute('''
SELECT sample_date, min_temp, max_temp, avg_temp
FROM weather_data
WHERE location = ?
''', (location,))
data = cursor.fetchall()
self.logger.info("Data fetched successfully.")
return data
except sqlite3.Error as error:
self.logger.error("An error occurred while fetching data from the database: %s",
error)
return []
def fetch_data_year_to_year(self, first_year, last_year):
'''
Fetch weather data from the SQLite database for a specified year range.
Parameters:
- first_year: int, the first year in the range.
- end_year: int, the final year in the range.
Returns:
- A list of data that falls in the range of years specified by the user.'''
month_data = {1:[], 2:[], 3:[], 4:[], 5:[], 6:[],
7:[], 8:[], 9:[], 10:[], 11:[], 12:[]}
start_year = f'{first_year}-01-01'
end_year = f'{last_year}-01-01'
with self.get_cursor() as cursor:
try:
for row in cursor.execute('''
SELECT sample_date, avg_temp
FROM weather_data
WHERE sample_date BETWEEN ? AND ?
ORDER BY sample_date''',(start_year, end_year)):
month = parser.parse(row[0]).month
month_data[month].append(row[1])
self.logger.info("Data fetched successfully.")
return month_data
except sqlite3.Error as error:
self.logger.error("An error occurred while fetching data from the database: %s",
error)
return []
def fetch_data_single_month(self, month, year):
'''
Fetch weather data from the SQLite database for a specified month and year.
Parameters:
- month: int, the month to search for.
- year: int, the year to search for.
Returns:
- A list of temperatures for the month and year the user searched for'''
temperatures = {}
with self.get_cursor() as cursor:
try:
for row in cursor.execute('''
SELECT sample_date, avg_temp
FROM weather_data
WHERE sample_date LIKE ?||'-'||'0'||?||'-'||'%'
ORDER BY sample_date''',(year, month)):
temperatures[row[0]] = row[1]
return temperatures
except sqlite3.Error as error:
self.logger.error("An error occurred while fetching data from the database: %s",
error)
return []
def get_latest_date_in_db(self):
with self.get_cursor() as cursor:
cursor.execute("SELECT MAX(sample_date) FROM weather_data")
latest_date = cursor.fetchone()[0]
print(latest_date)
return latest_date
# def get_dates(self) -> list:
# "Grabs all the dates from database"
# try:
# dates = []
# sql = ("""SELECT sample_date
# FROM weather_data
# ORDER BY sample_date;""")
# with DBCM("weather.sqlite") as conn:
# for row in conn.execute(sql):
# dates.append(row[0])
# return dates
# except Exception as error:
# self.logger.error("DBOps:get_dates:%s", error)
def purge_data(self):
"""
Purge all weather data from the SQLite database.
"""
with self.get_cursor() as cursor:
try:
cursor.execute('DELETE FROM weather_data')
self.logger.info("Data purged successfully.")
except sqlite3.Error as error:
self.logger.error("An error occurred while purging data from the database: %s",
error)
def get_cursor(self):
"""
Get a cursor to use for database operations.
Returns:
- A cursor object for the SQLite database.
"""
return DBCM(self.dbname)
class DBCM:
'''
A class that represents a connection to a database.
'''
def init(self, dbname):
self.dbname = dbname
self.logger = logging.getLogger(name)
def __enter__(self):
try:
self.conn = sqlite3.connect(self.dbname)
self.cursor = self.conn.cursor()
self.logger.info("Connection to database established successfully.")
return self.cursor
except sqlite3.Error as error:
self.logger.error("An error occurred while connecting to the database: %s", error)
return None
def __exit__(self, exc_type, exc_val, exc_tb):
if exc_type is not None:
self.conn.rollback()
else:
try:
self.conn.commit()
self.logger.info("Changes committed successfully.")
except sqlite3.Error as error:
self.logger.error("An error occurred while committing changes to the database: %s",
error)
try:
self.cursor.close()
self.conn.close()
self.logger.info("Connection to database closed successfully.")
except sqlite3.Error as error:
self.logger.error("An error occurred while closing the database connection: %s", error)
def main():
'''
The main method.
'''
# Initialize the database
data_base = DBOperations("mydatabase.db")
data_base.initialize_db()
# Get the weather data
scraper = WeatherScraper()
data = scraper.get_data()
# Process the data and prepare the rows
rows = []
for date, temps in data.items():
row = (
date,
"Winnipeg",
temps["Max"],
temps["Min"],
temps["Mean"]
)
rows.append(row)
# Save the data to the database
with data_base.get_cursor() as cursor:
try:
cursor.executemany('''
INSERT OR IGNORE INTO weather_data
(sample_date, location, min_temp, max_temp, avg_temp)
VALUES (?, ?, ?, ?, ?)
''', rows)
data_base.logger.info("Inserted %s rows into the database.", len(rows))
except sqlite3.Error as error:
data_base.logger.error("An error occurred while inserting data: %s", error)
if name == 'main':
main()
from plot_operations import PlotOperations
import sys
import logging
from datetime import datetime, timedelta
from scrape_weather import WeatherScraper
from db_operations import DBOperations
from plot_operations import PlotOperations
from dateutil import parser
def main_menu(self):
while True:
print("\nWeather Data Processor")
print("1. Download a full set of weather data")
print("2. Update weather data")
print("3. Generate box plot based on year range")
print("4. Generate line plot based on a month and year")
print("5. Exit")
selection = input("Make a selection: ")
if selection == "1":
self.download_full_set()
input("Press Enter to continue...")
elif selection == "2":
self.update_weather_data()
input("Press Enter to continue...")
elif selection == "3":
self.generate_box_plot()
input("Press Enter to continue...")
elif selection == "4":
self.generate_line_plot()
input("Press Enter to continue...")
elif selection == "5":
sys.exit(0)
else:
print("Invalid choice. Select another option.")
def download_full_set(self):
data = self.scrape_weather.get_data()
self.db_operations.save_data(data)
#TODO
def update_weather_data(self):
# Get the latest entry from the database
latest_date_in_db = self.db_operations.get_latest_date_in_db()
if latest_date_in_db:
# If there is a latest entry, get its date
latest_date_in_db = datetime.strptime(latest_date_in_db, '%Y-%m-%d').date()
today_date = datetime.now().date()
# Compare the latest date to the current date
if latest_date_in_db != today_date:
# If the latest date is not the current date, fetch the weather data
data = self.scrape_weather.get_data()
# Save the weather data to the database
self.db_operations.save_data(data)
# self.update_weather_data()
else:
# If there is no latest entry, fetch the weather data
data = self.scrape_weather.get_data()
# Save the weather data to the database
self.db_operations.save_data(data)
# Update the weather data
# self.update_weather_data()
def generate_box_plot(self):
start_year = input("Enter the year to start gathering data from: ")
end_year = input("Enter the year to end the search for data at: ")
data = self.db_operations.fetch_data_year_to_year(start_year, end_year)
self.create_plot.create_box_plot(start_year, end_year, data)
def generate_line_plot(self):
month = input("Enter a month to search for weather data (January = 1, February = 2): ")
year = input("Enter the year of the month you wish to view data from: ")
data = self.db_operations.fetch_data_single_month(month, year)
self.create_plot.create_line_plot(data)
if name == 'main':
processor = WeatherProcessor()
processor.main_menu()
The PlotOperations class is imported but not provided in the code, so it can be assumed that it is a separate module that is responsible for creating the box and line plots.
Overall, these classes provide a comprehensive solution for scraping weather data, storing the data in a database, and creating visualizations based on the stored data.
This code first checks if there is a latest date in the database. If so, it calculates the difference between that date and the current date. If the difference is greater than 0, it sets the initial_date attribute of the WeatherScraper instance to the latest date in the database, enabling it to start scraping the missing data between those dates. Finally, the scraped data is saved to the database using the save_data() function.
Now you can update the WeatherProcessor class to call the update_weather_data function from the DBOperations instance:
class WeatherProcessor:
...
def update_weather_data(self):
self.db_operations.update_weather_data(self.scrape_weather)
This design better encapsulates the database-related functionality within the DBOperations class, making the code more modular and easier to maintain.
initial_date
get_data()
WeatherScraper
Modify the WeatherScraper class by adding a new attribute end_date and initializing it in the __init__() method:
class WeatherScraper(HTMLParser):
...
def __init__(self):
try:
super().__init__()
...
self.initial_date = None
self.end_date = None # Add this line
except Exception as error:
self.logger.error("scrape:init:%s", error)
...
Update the get_data() method to iterate forward from the initial_date to end_date:
class WeatherScraper(HTMLParser):
...
def get_data(self):
if self.initial_date is None:
current_date = datetime.now()
else:
current_date = self.initial_date
# Set end_date to today's date if not specified
if self.end_date is None:
end_date = datetime.now()
else:
end_date = self.end_date
while current_date <= end_date: # Update this comparison
try:
...
# Update the date increment
current_date += timedelta(days=1) # Change from subtraction to addition
except Exception as error:
self.logger.error("scrape:get_data:%s", error)
return self.weather
...
Update the update_weather_data() method in the DBOperations class to set the initial_date and the end_date attributes of the WeatherScraper instance:
class DBOperations:
...
def update_weather_data(self, weather_scraper):
...
if days_difference > 0:
# Set the initial_date and end_date attributes
weather_scraper.initial_date = latest_date_in_db + timedelta(days=1)
weather_scraper.end_date = today_date
# Scrape the missing weather data
data = weather_scraper.get_data()
...
...
By adding the end_date attribute and modifying the get_data() method to iterate forward from initial_date to end_date, you can now fetch the missing data from the latest date in the database up to the current date. In the DBOperations class, you can set the initial_date and end_date attributes using the WeatherScraper instance before calling the get_data() method to ensure that the correct range of dates is scraped.
WeatherScraper
To gather data from a specific start date and until today, set the initial_date attribute in the WeatherScraper instance before calling the get_data() method:
# Set the initial_date attribute for the instance
scraper.initial_date = datetime(2000, 1, 1).date()
# Fetch the weather data
data = scraper.get_data()
In this example, the scraper will gather all the data from January 1, 2000, until today.