The user wants a Python web scraper to collect weather data and store it in an SQLite database.
-
Identify the Goal: Scrape weather data from a specific website and save it to a local SQLite database.
-
Select the Target Website:
- I need a site that is easy to scrape (static HTML is best for a simple example, though real-world sites often use JS).
- Open-Meteo is a good choice because it has a free, non-commercial API, but the user asked for a scraper, not an API client.
- Weather.com and AccuWeather are heavily protected by anti-bot measures (Cloudflare, dynamic classes).
- TimeandDate.com is a solid choice for scraping because the HTML structure is relatively stable and readable.
- Wunderground is also good but can be tricky.
- Decision: I will use a generic example or a specific page like "TimeandDate.com" for a specific city (e.g., New York) to demonstrate the concept clearly. I will add a disclaimer about respecting
robots.txt and terms of service.
-
Choose the Tools:
- Language: Python (specified).
- Scraping Library:
requests (to fetch HTML) and BeautifulSoup (to parse HTML). This is the standard beginner-friendly stack. playwright or selenium are too heavy for a simple example unless JS rendering is required. I'll stick to requests + bs4.
- Database:
sqlite3 (built-in Python library).
- Data Structure: Date, Time, Temperature, Condition.
-
Drafting the Code Structure:
- Step 1: Setup/Imports. Import
sqlite3, requests, BeautifulSoup.
- Step 2: Database Setup. Create a connection, create a table if it doesn't exist.
- Step 3: The Scraper.
- Define the URL (User-Agent header is crucial to avoid immediate 403s).
- Fetch content.
- Parse with BeautifulSoup.
- Extraction Logic: Inspect a typical weather page. I'll simulate a generic extraction or use a specific class structure from a site like TimeandDate. Let's use a specific example for the code to work immediately. Let's try scraping "London" weather from TimeandDate.
- Refinement: To make the code robust, I should handle errors.
- Step 4: Storage. Insert the extracted data into the SQLite table. Commit changes.
- Step 5: Verification. Query the DB to show it worked.
-
Writing the Code (Mental Draft):
- URL:
https://www.timeanddate.com/weather/uk/london/historic (or current).
- Actually, let's keep it generic so the user understands the logic, but provide a working URL.
- Let's use the National Weather Service (weather.gov) as it's a public service and generally permits scraping for educational purposes, or a simpler test site like
books.toscrape.com but that's not weather.
- Let's go back to TimeandDate. It's visual.
- Target:
https://www.timeanddate.com/weather/ -> h1 for city, .h2 for temp.
-
Refining the Code for the Output:
- I need to make sure the SQL table schema matches the scraped data.
- Columns:
id (PK), city, temperature, description, humidity, scraped_at.
-
Constructing the Explanation:
- Prerequisites: Install
requests and beautifulsoup4.
- Step-by-Step:
- Database creation function.
- Scraping function (User-Agent is key).
- Main execution block.
- Ethical Note: Always mention
robots.txt and not overloading servers.
-
Self-Correction/Review during drafting:
- Issue: Websites change classes frequently.
- Solution: I will add comments explaining that CSS selectors might need updating. I will try to use selectors that are likely to stick around (like IDs or semantic tags).
- Choice of Site for Code: I'll use Open-Meteo's website (not API) or TimeandDate as they are accessible. Let's go with TimeandDate for a specific city (e.g., New York) because it usually renders server-side (or easily accessible) data.
- Wait, TimeandDate uses a lot of JS for detailed tables.
- Alternative: Wikipedia's "Current events" or a specific weather page? No.
- Better Alternative: Let's write a script for a mockup structure or use National Weather Service (weather.gov) because their HTML is very standard and text-based.
- Let's stick to a robust scraping logic using
weather.gov (NOAA).
- URL:
https://forecast.weather.gov/MapClick.php?CityName=New+York&state=NY (or a specific lat/lon station).
- Selectors:
- Location:
h2
- Temp:
.myforecast-current-lrg
- Description:
.myforecast-current
-
Finalizing Code Structure (using weather.gov as the example target):
- It's a US government site, reliable, English, and legal to scrape for personal use.
- Imports:
requests, bs4, sqlite3, datetime.
- DB: Table
weather_data.
- Request: Add
User-Agent.
- Parse: BS4.
- Store: SQL INSERT.
-
Adding Output: The user needs to see how to read the data back, so I'll add a "read" function at the end.
-
Formatting: Use Markdown code blocks. Add comments.
(Self-Correction during final check): Ensure I handle the case where the element isn't found so the script doesn't crash immediately without explanation.
-
Final Polish: Add instructions on how to run it.
pip install requests beautifulsoup4
- Run script.
Let's write the response following this structure.
Here is a complete, step-by-step guide to building a Python web scraper that collects weather data and stores it in a SQLite database.
We will use the National Weather Service (weather.gov) as our target because it is a public service, text-friendly, and allows scraping for educational purposes.
Prerequisites
You will need to install two external libraries: requests (to get the website code) and beautifulsoup4 (to read it).
Open your terminal and run:
pip install requests beautifulsoup4
The Python Script
Here is the complete script. It defines a database, scrapes the current temperature and description for a specific location, and saves it.
import sqlite3
import requests
from bs4 import BeautifulSoup
from datetime import datetime
# --- Configuration ---
# We will scrape the forecast for New York City (Central Park)
URL = "https://forecast.weather.gov/MapClick.php?lat=40.7826&lon=-73.9654"
DB_NAME = "weather_data.db"
def setup_database():
"""Creates the database and the table if they don't exist."""
conn = sqlite3.connect(DB_NAME)
cursor = conn.cursor()
# Create a table with columns for ID, time, temperature, and description
cursor.execute('''
CREATE TABLE IF NOT EXISTS weather_logs (
id INTEGER PRIMARY KEY AUTOINCREMENT,
timestamp DATETIME DEFAULT CURRENT_TIMESTAMP,
temperature REAL,
description TEXT
)
''')
conn.commit()
conn.close()
print(f"[*] Database '{DB_NAME}' checked/created.")
def scrape_weather():
"""Fetches the URL and extracts weather data."""
# Weather servers often block requests that don't look like a real browser.
# We add a 'User-Agent' header to mimic a browser.
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:
response = requests.get(URL, headers=headers)
response.raise_for_status() # Check for HTTP errors (like 404)
soup = BeautifulSoup(response.content, 'html.parser')
# --- Find Specific Data ---
# We are looking for the "Current Conditions" section on weather.gov
# Usually inside a div with id="current-conditions"
# 1. Find the temperature
# On this site, the current temp usually has class "myforecast-current-lrg"
temp_tag = soup.find("p", class_="myforecast-current-lrg")
temp_f = temp_tag.text.strip() if temp_tag else "N/A"
# 2. Find the description (e.g., "Sunny", "Partly Cloudy")
desc_tag = soup.find("p", class_="myforecast-current")
description = desc_tag.text.strip() if desc_tag else "N/A"
return temp_f, description
except Exception as e:
print(f"[!] Error scraping data: {e}")
return None, None
def save_to_db(temp, desc):
"""Inserts the scraped data into SQLite."""
conn = sqlite3.connect(DB_NAME)
cursor = conn.cursor()
cursor.execute('''
INSERT INTO weather_logs (temperature, description)
VALUES (?, ?)
''', (temp, desc))
conn.commit()
conn.close()
print(f"[*] Saved to DB: Temp {temp} | Desc: {desc}")
def main():
# 1. Setup
setup_database()
# 2. Scrape
print(f"[*] Scraping {URL}...")
temperature, description = scrape_weather()
# 3. Store
if temperature and description:
save_to_db(temperature, description)
# 4. Verification (Optional: Print last 5 entries from DB)
print("\n--- Last 5 Database Entries ---")
conn = sqlite3.connect(DB_NAME)
cursor = conn.cursor()
cursor.execute("SELECT * FROM weather_logs ORDER BY id DESC LIMIT 5")
rows = cursor.fetchall()
for row in rows:
print(row)
conn.close()
else:
print("[!] No data fetched.")
if __name__ == "__main__":
main()
How It Works
-
setup_database:
- Connects to
weather_data.db. If the file doesn't exist, SQLite creates it automatically.
- Creates a table named
weather_logs with columns for an ID, the time the data was fetched, the temperature, and the weather description.
-
scrape_weather:
- Headers: Websites often block Python scripts to save bandwidth. We send a
User-Agent header so the website thinks the request is coming from Google Chrome.
- Requests: Downloads the HTML code of the webpage.
- BeautifulSoup: Parses the raw HTML text into a tree structure we can search.
- Selectors: We use
soup.find() with specific CSS classes (myforecast-current-lrg) to locate the exact text we want.
-
save_to_db:
- Connects to the database again.
- Runs a SQL
INSERT command to add the new temperature and description as a new row.
How to Find the Selectors (For other websites)
If you want to scrape a different site, you need to find the "Class" or "ID" of the HTML element containing the data.
- Open the website in your browser (e.g., Chrome).
- Right-click on the Temperature number.
- Select Inspect.
- A panel will open showing the HTML. Look for
class="...".
- Example:
<span class="current-temp">55°F</span>
- Update the
soup.find line in the script:
soup.find("span", class_="current-temp")
How to Run It
Save the code as weather_scraper.py and run:
python weather_scraper.py
You should see output indicating the data was saved, followed by a printout of the database contents. You can run it multiple times to build up a history of logs.