The user wants to build a Python web scraper for weather data, but they haven't specified the site, frequency, or OS. I think a generic solution using requests and BeautifulSoup could work, like scraping from weather.gov or wttr.in. However, I'll need to ensure we’re compliant with ToS and robots.txt.
I should provide a template that users can easily adapt. The final code might make use of an API, like open-meteo.com, to align with best practices. Nonetheless, since the user requested a web scraper, I’ll include a basic pattern for scraping simple HTML, assuming permission is granted.Encouraging responsible scraping
I believe it's essential to encourage reading the robots.txt file and terms of service (ToS) before scraping. I can outline a script that uses the requests library and BeautifulSoup4 to parse weather data like location, temperature, humidity, and conditions, then save this info into an SQLite database with sqlite3.
For simplicity, I might choose a static URL example, like "https://example.com/weather/tokyo." However, there are services like wttr.in that allow easy text queries and explicitly permit CLI usage. Even though it’s more like using an API, I can still treat this as scraping.Adjusting for generic web scraping
I think it’s better to demonstrate how to adjust selectors for different sites without tying to a specific one, which helps avoid ToS issues. The user requested a Python web scraper for weather data and to store it in SQLite, possibly wanting a step-by-step guide.
I’ll cover environment setup, database schema, scraping logic, and scheduling. I need to remind the user to check the website's legalities and suggest using an open API. I'll provide installation instructions for necessary packages and outline functions, keeping the CSS selectors generic. While an example could be wttr.in, it returns JSON rather than HTML.Choosing a suitable scraping example
I’m considering using https://wttr.in/{city}, which returns ANSI art, but parsing that might be tricky since it requires text parsing. Another option could be open-meteo.com, though they’re API-focused. I could use a dummy HTML example and suggest users update selectors accordingly, but that might feel unsatisfying.
Since the user wants fully working code for scraping, I might go with https://forecast.weather.gov. Their page has accessible HTML and CSS selectors, and their ToS generally allow open use of NWS data. I'll remind users to still check the robots.txt file for compliance.Building a weather scraper script
I'll create a Python weather scraper targeting the National Weather Service at this URL: https://forecast.weather.gov/MapClick.php?lat=40.7146&lon=-74.0071 (for NYC). The structure includes elements like div id="current_conditions-summary" and different p tags for parsing weather data.
I’ll provide a complete script, including installation instructions for required packages, database setup, and methods to fetch and parse weather info. I plan to include reminders about respecting robots.txt and ToS, and encourage best practices for scraping intermittently. I'll also design the code to be adaptable to different locations and selectors. Below is a complete, minimal example of a Python scraper that:
Fetches current weather data from a web page
Parses it with BeautifulSoup
Stores it in a SQLite database
You can adapt the URL and CSS selectors for whatever site you’re allowed to scrape.
1. Prerequisites
Install Python 3 (if not already installed).
Install required libraries:
bash
pip install requests beautifulsoup4
SQLite is built into Python (sqlite3), so no extra install is needed.
Important:
Before scraping any real website, check its Terms of Service and robots.txt, and keep your request rate low.
2. Full script: weather_scraper.py
This example uses a National Weather Service forecast page (which, as of my knowledge cutoff, provides open data).
Replace the URL and CSS selectors as needed for your target site.
python
3. How to run it
bash
python weather_scraper.py
You should see:
The parsed weather data printed
A weather.db file created in the current directory
The latest 5 rows printed from the database
4. Customizing for another website
If you want to target another site:
Change WEATHER_URL to the desired page.
Inspect the page’s HTML in your browser (right-click → “Inspect”).
Update the selectors in parse_weather() to match that site:
soup.select_one("...") / soup.find("...")
Look for the elements that hold temperature, condition, humidity, etc.
For multiple locations, you could do something like:
python
LOCATIONS = {
"New York, NY": "https://forecast.weather.gov/MapClick.php?lat=40.7146&lon=-74.0071",
"Los Angeles, CA": "https://forecast.weather.gov/MapClick.php?lat=34.0522&lon=-118.2437",
}
for name, url in LOCATIONS.items():
html = fetch_page(url)
data = parse_weather(html)
data["location"] = name # override with your label if you prefer
save_weather(conn, data)
If you tell me the specific website and data fields you want, I can tailor the selectors and schema exactly to that.
import sqlite3
from datetime import datetime, timezone
from pathlib import Path
import requests
from bs4 import BeautifulSoup
# ==========================
# Configuration
# ==========================
DB_PATH = Path("weather.db")
# Example: New York City forecast page on weather.gov (change this for your location)
WEATHER_URL = (
"https://forecast.weather.gov/MapClick.php?lat=40.7146&lon=-74.0071"
)
# Identify yourself politely; some servers use this
HEADERS = {
"User-Agent": "WeatherScraper/1.0 (contact: your-email@example.com)"
}
# ==========================
# Database functions
# ==========================
def init_db(db_path: Path = DB_PATH) -> sqlite3.Connection:
"""Create/open the SQLite database and ensure the table exists."""
conn = sqlite3.connect(db_path)
conn.execute(
"""
CREATE TABLE IF NOT EXISTS weather (
id INTEGER PRIMARY KEY AUTOINCREMENT,
location TEXT NOT NULL,
temperature_f REAL,
condition TEXT,
humidity INTEGER,
wind TEXT,
scraped_at_utc TEXT NOT NULL
)
"""
)
conn.commit()
return conn
def save_weather(conn: sqlite3.Connection, data: dict) -> None:
"""Insert one weather record into the database."""
now = datetime.now(timezone.utc).isoformat()
conn.execute(
"""
INSERT INTO weather (location, temperature_f, condition, humidity, wind, scraped_at_utc)
VALUES (?, ?, ?, ?, ?, ?)
""",
(
data.get("location"),
data.get("temperature_f"),
data.get("condition"),
data.get("humidity"),
data.get("wind"),
now,
),
)
conn.commit()
# ==========================
# Scraping functions
# ==========================
def fetch_page(url: str) -> str:
"""Download the HTML page."""
resp = requests.get(url, headers=HEADERS, timeout=15)
resp.raise_for_status()
return resp.text
def parse_weather(html: str) -> dict:
"""
Parse weather data from the HTML.
This is tailored to a typical weather.gov forecast page.
For a different site, adjust the CSS selectors/XPaths.
"""
soup = BeautifulSoup(html, "html.parser")
# Location: usually in an <h2 class="panel-title">
location_el = soup.select_one("h2.panel-title")
location = location_el.get_text(strip=True) if location_el else "Unknown location"
# Current condition text: e.g. "Partly Cloudy"
cond_el = soup.select_one("p.myforecast-current")
condition = cond_el.get_text(strip=True) if cond_el else None
# Current temperature in F: e.g. "55°F"
temp_el = soup.select_one("p.myforecast-current-lrg")
temperature_f = None
if temp_el:
raw = temp_el.get_text(strip=True)
# extract digits, '.', and '-' from "55°F" -> "55"
digits = "".join(ch for ch in raw if ch.isdigit() or ch in ".-")
if digits:
try:
temperature_f = float(digits)
except ValueError:
temperature_f = None
# Humidity (and other details are usually in a table under #current_conditions_detail)
humidity = None
wind = None
details_table = soup.select_one("#current_conditions_detail")
if details_table:
# Find the table cell whose text is "Humidity" then read its sibling cell
humid_label = details_table.find("td", string=lambda s: s and "Humidity" in s)
if humid_label:
humid_value_cell = humid_label.find_next_sibling("td")
if humid_value_cell:
h_text = humid_value_cell.get_text(strip=True)
# "65%" -> 65
h_digits = "".join(ch for ch in h_text if ch.isdigit())
if h_digits:
try:
humidity = int(h_digits)
except ValueError:
humidity = None
# Wind speed
wind_label = details_table.find("td", string=lambda s: s and "Wind Speed" in s)
if wind_label:
wind_value_cell = wind_label.find_next_sibling("td")
if wind_value_cell:
wind = wind_value_cell.get_text(strip=True)
return {
"location": location,
"temperature_f": temperature_f,
"condition": condition,
"humidity": humidity,
"wind": wind,
}
# ==========================
# Main entry point
# ==========================
def main():
conn = init_db()
try:
html = fetch_page(WEATHER_URL)
except requests.RequestException as e:
print(f"Error fetching page: {e}")
return
data = parse_weather(html)
# Simple sanity check
print("Parsed data:", data)
save_weather(conn, data)
print("Saved to SQLite:", DB_PATH.resolve())
# Show the most recent entries
print("\nLast 5 records:")
for row in conn.execute(
"SELECT id, location, temperature_f, condition, humidity, wind, scraped_at_utc "
"FROM weather ORDER BY id DESC LIMIT 5"
):
print(row)
conn.close()
if __name__ == "__main__":
main()