#!/usr/bin/env python3
"""
Sherlock's Weather Scraper
==========================
A Python web scraper that:
- Geocodes a city name using Open-Meteo's free geocoding API.
- Fetches current weather data using Open-Meteo's free forecast API (JSON over HTTP).
- Stores the data in a local SQLite database.
No API keys required. Units: Fahrenheit and MPH.
Usage:
python weather_scraper.py "New York"
python weather_scraper.py "London"
To view data:
sqlite3 weather.db "SELECT * FROM weather ORDER BY timestamp DESC LIMIT 10;"
Dependencies: requests (pip install requests), sqlite3/datetime (standard library).
"""
import requests
import sqlite3
import sys
from datetime import datetime
from urllib.parse import quote
def init_db(db_path='weather.db'):
"""Initialize SQLite database and create weather table if it doesn't exist."""
conn = sqlite3.connect(db_path)
cursor = conn.cursor()
cursor.execute('''
CREATE TABLE IF NOT EXISTS weather (
id INTEGER PRIMARY KEY AUTOINCREMENT,
timestamp TEXT NOT NULL,
city TEXT NOT NULL,
latitude REAL NOT NULL,
longitude REAL NOT NULL,
temperature REAL NOT NULL,
windspeed REAL NOT NULL,
weathercode INTEGER NOT NULL,
timezone TEXT NOT NULL
)
''')
conn.commit()
conn.close()
def geocode_city(city):
"""Geocode city name to lat/lon/timezone using Open-Meteo Geocoding API."""
url = f"https://geocoding-api.open-meteo.com/v1/search?name={quote(city)}&count=1&language=en&format=json"
response = requests.get(url)
response.raise_for_status()
data = response.json()
if 'results' not in data or not data['results']:
raise ValueError(f"City '{city}' not found.")
result = data['results'][0]
return result['latitude'], result['longitude'], result['timezone']
def get_current_weather(lat, lon, tz):
"""Fetch current weather using Open-Meteo Forecast API."""
url = (
f"https://api.open-meteo.com/v1/forecast?"
f"latitude={lat}&longitude={lon}&"
f"current_weather=true&"
f"temperature_unit=fahrenheit&"
f"windspeed_unit=mph&"
f"timezone={quote(tz)}"
)
response = requests.get(url)
response.raise_for_status()
data = response.json()
current = data['current_weather']
return (
current['temperature'],
current['windspeed'],
current['weathercode']
)
def store_weather(city, lat, lon, tz, temp, windspeed, weathercode, db_path='weather.db'):
"""Store weather data in SQLite."""
timestamp = datetime.utcnow().isoformat() # UTC for consistency
conn = sqlite3.connect(db_path)
cursor = conn.cursor()
cursor.execute('''
INSERT INTO weather (timestamp, city, latitude, longitude, temperature, windspeed, weathercode, timezone)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
''', (timestamp, city, lat, lon, temp, windspeed, weathercode, tz))
conn.commit()
conn.close()
def main():
if len(sys.argv) != 2:
print("Usage: python weather_scraper.py 'City Name'")
print("Example: python weather_scraper.py 'New York'")
sys.exit(1)
city = sys.argv[1].strip()
try:
init_db()
lat, lon, tz = geocode_city(city)
temp, windspeed, weathercode = get_current_weather(lat, lon, tz)
store_weather(city, lat, lon, tz, temp, windspeed, weathercode)
print(f"✅ Weather data for '{city}' stored successfully!")
print(f" 📍 {city} ({lat:.4f}, {lon:.4f}) | TZ: {tz}")
print(f" 🌡️ Temperature: {temp}°F")
print(f" 💨 Windspeed: {windspeed} mph")
print(f" ☁️ Weathercode: {weathercode}")
print(f" 🕐 Timestamp: {datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S UTC')}")
print("\n💾 Data stored in 'weather.db'. Run multiple times to collect history.")
except requests.RequestException as e:
print(f"❌ Network error: {e}")
except ValueError as e:
print(f"❌ {e}")
except Exception as e:
print(f"❌ Unexpected error: {e}")
if __name__ == "__main__":
main()
Quick Start
- Save as
weather_scraper.py.
pip install requests (if needed).
- Run:
python weather_scraper.py "London".
- Data is stored in
weather.db (portable SQLite file).
- Weathercode meanings (Open-Meteo WMO codes): 0=Clear sky, 1=Mainly clear, 2=Partly cloudy, 3=Overcast, 45=Fog, 48=Rime fog, 51-99=Drizzle/rain/snow/hail, etc. Full list: https://open-meteo.com/en/docs.
Enhancements You Can Add
- Scheduling: Use
schedule lib or cron: while True: main(); time.sleep(3600) for hourly.
- Multiple cities:
python weather_scraper.py "New York,London,Tokyo".
- Historical data: Add
hourly=temperature_2m param, store arrays.
- Pure HTML scraping: Swap APIs for
BeautifulSoup(requests.get('https://wttr.in/London?format=3').text).
This is robust, efficient, and respects rate limits (Open-Meteo allows ~10k calls/day). Questions? Ask away! 🕵️♂️