I'm focused on the initial scoping of this Python web scraping project. My primary focus right now is understanding the user's requirements: scraping weather data and storing it in an SQLite database. I'm starting to identify the necessary components, such as using Python as the core language.
Detailing the Implementation Steps
I've outlined the project in detail, breaking it down into manageable steps: setting up the imports, initializing the database, creating the main scraping function, and extracting specific weather data. I will be using the NWS website as the target for this scraping. The forecast containers will be targeted to extract the forecast period, short description and temperature.
Formulating the Code's Structure
I'm now focusing on the code's structural design. I've decided to break the project into modules: one for database interactions, another for the scraping logic, and a main function to orchestrate the process. Error handling is critical here. It seems best to include try/except blocks around network requests and HTML parsing to make it robust. I will also incorporate custom headers to avoid bot detection.
Planning the Data Extraction
I'm now zeroing in on the data extraction phase. I've pinpointed the necessary HTML elements within the NWS forecast page using their class names, like 'period-name', 'short-desc', and 'temp'. The SQLite database will store this data. I have also decided to add a timestamp to the stored data.
Evaluating the Code's Functionality
I'm now focusing on evaluating the planned code's efficiency. I'm considering potential issues, such as rate limits on the NWS site and how to best structure error handling to handle these gracefully. I also need to ensure the database can store a large amount of data without performance degradation. I will add a timestamp to the data for analysis.
This is a complete solution using the requests library to fetch data, BeautifulSoup to parse the HTML, and the built-in sqlite3 library to store the data.
For this example, we will scrape the National Weather Service (NWS) website, as it contains public domain data with a static HTML structure that is excellent for learning.
Prerequisites
You will need to install the external libraries. Open your terminal and run:
bash
pip install requests beautifulsoup4
The Python Script
Save this code as weather_scraper.py.
python
import requests
from bs4 import BeautifulSoup
import sqlite3
from datetime import datetime
# --- Configuration ---
TARGET_URL = "https://forecast.weather.gov/MapClick.php?lat=37.7772&lon=-122.4168" # San Francisco
DB_NAME = "weather_data.db"
def setup_database():
"""Creates the database and table if they don't exist."""
conn = sqlite3.connect(DB_NAME)
cursor = conn.cursor()
# Create table with columns for period, description, temp, and scraping time
cursor.execute('''
CREATE TABLE IF NOT EXISTS forecast (
id INTEGER PRIMARY KEY AUTOINCREMENT,
period TEXT,
short_desc TEXT,
temperature TEXT,
scraped_at TIMESTAMP
)
''')
conn.commit()
conn.close()
print(f"Database '{DB_NAME}' checks complete.")
def save_to_db(data_list):
"""Inserts a list of dictionary data into SQLite."""
conn = sqlite3.connect(DB_NAME)
cursor = conn.cursor()
current_time = datetime.now()
for item in data_list:
cursor.execute('''
INSERT INTO forecast (period, short_desc, temperature, scraped_at)
VALUES (?, ?, ?, ?)
''', (item['period'], item['short_desc'], item['temp'], current_time))
conn.commit()
conn.close()
print(f"Successfully saved {len(data_list)} rows to database.")
def scrape_weather():
"""Fetches HTML, parses it, and returns a list of weather data."""
print("Fetching weather data...")
# Use a User-Agent to look like a real browser (avoids basic blocking)
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36"
}
try:
page = requests.get(TARGET_URL, headers=headers)
page.raise_for_status() # Check for 404 or 500 errors
except requests.exceptions.RequestException as e:
print(f"Error fetching URL: {e}")
return []
soup = BeautifulSoup(page.content, 'html.parser')
# Find the HTML container identifying the 7-day forecast
# Note: This ID is specific to weather.gov
seven_day = soup.find(id="seven-day-forecast")
if not seven_day:
print("Could not find the forecast container on the page.")
return []
forecast_items = seven_day.find_all(class_="tombstone-container")
scraped_data = []
for item in forecast_items:
try:
# Extract text and clean it
period = item.find(class_="period-name").get_text(separator=" ").strip()
short_desc = item.find(class_="short-desc").get_text(separator=" ").strip()
# Temp might be "High" or "Low", check which exists
temp = item.find(class_="temp")
temp_text = temp.get_text() if temp else "N/A"
weather_obj = {
"period": period,
"short_desc": short_desc,
"temp": temp_text
}
scraped_data.append(weather_obj)
except AttributeError:
continue # Skip if an item is malformed
return scraped_data
def view_data():
"""Helper function to print what is currently in the DB."""
conn = sqlite3.connect(DB_NAME)
cursor = conn.cursor()
print("\n--- Current Database Content (Last 5 entries) ---")
cursor.execute("SELECT period, temperature, scraped_at FROM forecast ORDER BY id DESC LIMIT 5")
rows = cursor.fetchall()
for row in rows:
print(row)
conn.close()
# --- Main Execution Flow ---
if __name__ == "__main__":
# 1. Setup DB
setup_database()
# 2. Scrape Data
data = scrape_weather()
# 3. Save Data if scraping was successful
if data:
save_to_db(data)
# 4. Verify
view_data()
else:
print("No data scraped.")
How it works
requests.get: Connects to the website and downloads the raw HTML. We verify the connection was successful using .raise_for_status().
BeautifulSoup: This library takes the raw HTML string and turns it into a tree defining the structure of the webpage.
CSS Selectors:
We look for id="seven-day-forecast" (the main box on the NWS site).
Inside that, we loop through every item with the class tombstone-container.
We extract the specific text classes: period-name (e.g., Today), short-desc (e.g., Sunny), and temp.
sqlite3:
We create a file named weather_data.db.
We use Parameterized Queries (VALUES (?, ?, ?)). This is critical for security to prevent SQL Injection issues, even when just scraping data.
How to verify the data
After running the script, a file named weather_data.db will appear in your folder.
You can run the script multiple times. Because we added a scraped_at timestamp column, you will see a history of how the weather forecast changed over time in your database.
Important Note on Web Scraping
Stability: Websites change their HTML structure frequently. If the NWS updates their website design, the find(id=...) or class_ names in this script will break and need to be updated.
JavaScript: This script works for Static HTML sites (like NWS). If you try to scrape a site that relies heavily on JavaScript (like React or Angular apps), requests will not find the data. For those, you would need a tool like Selenium or Playwright.
Etiqutte: Always check a website's /robots.txt file (e.g., weather.gov/robots.txt) to see if they allow scraping. Do not hammer the server with thousands of requests per second.