Build a weather scraper for a site that loads data via… · The Chat Archive
Explore Build a weather scraper for a site that loads data via JavaScript. Use Selenium Wire or… Save Share Download ▾ ReportBuild a weather scraper for a site that loads data via JavaScript. Use Selenium Wire or inspect network traffic to identify the internal API endpoint and fetch JSON directly from that API instead of scraping the DOM.
AssistantCopy response Copy first prompt Copy first response
Other models, same or similar prompt Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Details
Provider anthropic
Model provenance As recorded by source dataset
Turns 1 (2 messages)
Language —
Added to archive Nov 21, 2026
ID 01m7y97713pdjt2sqfr98pnbk3Source & license Imported from Frontier Reasoning Traces (source ). Imported records earn no Research Points.
Upstream record: train-0.parquet:10464
SultanR/frontier-reasoning-traces-sft, revision 0e6b23142b95f5fe.
License: Apache-2.0
Dataset releases Not yet included in a published release.
This is a great question about web scraping. The user wants me to build a weather scraper that:
Works with JavaScript-loaded content
Uses Selenium Wire or network inspection to find the API endpoint
Fetches JSON directly from the API instead of scraping DOM
I'll create a comprehensive example that demonstrates:
Using Selenium Wire to capture network traffic
Identifying API endpoints
Fetching data directly from the API
Proper error handling and headers
Example with a popular weather site
Let me build this step by step with multiple approaches:
First, an example using Selenium Wire to find the API
Then direct API calls with proper headers
Include best practices for rate limiting and error handling
I'll use weather APIs or demonstrate with a hypothetical weather site that loads data via JS.
Weather Scraper with Selenium Wire & Direct API Fetching
I'll show you how to identify and extract data from JavaScript-loaded weather sites by capturing network traffic and calling the API directly.
1. Install Required Libraries
bash Copy code
pip install selenium-wire requests beautifulsoup4 lxml
# For Chrome WebDriver
pip install webdriver-manager
2. Find API Endpoint with Selenium Wire
python Copy code
"""
discover_weather_api.py
Use Selenium Wire to capture network requests and identify the API endpoint
"""
from seleniumwire import webdriver
from seleniumwire.utils import decode
import json
import time
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.chrome.service import Service
def discover_weather_api(url, search_terms=None):
"""
Capture network traffic to find the API endpoint
"""
if search_terms is None:
search_terms = ['weather', 'forecast', 'api', 'data']
# Configure Selenium Wire options
options = {
'disable_encoding': True, # Prevent gzip compression for easier inspection
}
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument('--no-sandbox')
chrome_options.add_argument('--disable-dev-shm-usage')
driver = webdriver.Chrome(
service=Service(ChromeDriverManager().install()),
chrome_options=chrome_options,
seleniumwire_options=options
)
try:
print(f"Loading {url}...")
driver.get(url)
# Wait for requests to complete
time.sleep(5)
# Analyze captured requests
print("\n" + "="*80)
print("CAPTURED REQUESTS")
print("="*80)
api_endpoints = []
for request in driver.requests:
# Look for JSON responses
if request.response:
try:
# Check if response contains JSON
if 'application/json' in request.response.headers.get('Content-Type', ''):
url_lower = request.url.lower()
# Filter by search terms
if any(term in url_lower for term in search_terms):
print(f"\n📡 API ENDPOINT FOUND:")
print(f" URL: {request.url}")
print(f" Method: {request.method}")
print(f" Status: {request.response.status_code}")
# Extract and display response body
try:
body = decode(
request.response.body,
request.response.headers.get('Content-Encoding', 'identity')
)
response_json = json.loads(body)
print(f" Response Preview:")
print(json.dumps(response_json, indent=2)[:500])
api_endpoints.append({
'url': request.url,
'method': request.method,
'headers': dict(request.headers),
'status': request.response.status_code,
'data_sample': response_json
})
except:
pass
except Exception as e:
pass
return api_endpoints
finally:
driver.quit()
if __name__ == "__main__":
# Example: Weather site
url = "https://weather.com"
endpoints = discover_weather_api(url)
if endpoints:
print("\n" + "="*80)
print("SUMMARY OF DISCOVERED ENDPOINTS")
print("="*80)
for i, endpoint in enumerate(endpoints, 1):
print(f"\n{i}. {endpoint['url']}")
3. Direct API Fetching (After Discovery)
4. Advanced: Selenium Wire with Request Filtering
5. Production-Ready Scraper
6. Configuration & Best Practices
python Copy code
"""
config.py
Configuration and best practices
"""
from dataclasses import dataclass
from typing import List
import os
from dotenv import load_dotenv
load_dotenv()
@dataclass
class ScraperConfig:
"""Configuration for weather scraper"""
# API Configuration
api_endpoint: str = os.getenv(
'WEATHER_API_ENDPOINT',
'https://api.weatherapi.com/v1/current.json'
)
api_key: str = os.getenv('WEATHER_API_KEY', '')
# Request Configuration
timeout: int = 10
retry_attempts: int = 3
retry_backoff: float = 1.5
# Rate Limiting
requests_per_minute: int = 60
requests_per_hour: int = 1000
# Caching
cache_enabled: bool = True
cache_ttl_hours: int = 6
cache_dir: str = './cache'
# Headers
user_agent: str = (
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) '
'AppleWebKit/537.36 (KHTML, like Gecko) '
'Chrome/91.0.4472.124 Safari/537.36'
)
# Selenium Wire
selenium_timeout: int = 15
disable_ssl_verification: bool = False
# Logging
log_level: str = 'INFO'
log_file: str = './logs/scraper.log'
@classmethod
def from_env(cls):
"""Load configuration from environment variables"""
return cls()
# Best practices checklist
BEST_PRACTICES = """
✓ IDENTIFICATION:
- Use browser DevTools Network tab to find API endpoints
- Look for XHR/Fetch requests with JSON responses
- Copy full URL including query parameters
✓ HEADER MANAGEMENT:
- Include User-Agent header (mimic real browser)
- Add Accept, Referer headers when needed
- Handle Authorization/API keys securely
✓ RATE LIMITING:
- Implement backoff strategies (exponential backoff)
- Respect API rate limit headers (X-RateLimit-*)
- Cache responses to minimize requests
✓ ERROR HANDLING:
- Handle connection timeouts
- Implement retry logic with exponential backoff
- Log failures for debugging
✓ DATA STORAGE:
- Use SQLite for local caching
- Structure data properly (JSON/CSV)
- Implement cache expiration (TTL)
✓ LEGAL/ETHICAL:
- Check website Terms of Service
- Don't overload servers with requests
- Respect robots.txt
- Use official APIs when available
- Consider rate limits and identify yourself
"""
if __name__ == "__main__":
print(BEST_PRACTICES)
config = ScraperConfig.from_env()
print(f"\nConfiguration loaded:")
print(f" API Endpoint: {config.api_endpoint}")
print(f" Cache TTL: {config.cache_ttl_hours} hours")
print(f" Max Requests/Minute: {config.requests_per_minute}")
7. Complete Example with Tests
python Copy code
"""
test_scraper.py
Unit tests for the weather scraper
"""
import unittest
from unittest.mock import patch, MagicMock
import json
from weather_api_fetcher import WeatherScraper
class TestWeatherScraper(unittest.TestCase):
"""Test cases for WeatherScraper"""
def setUp(self):
"""Set up test fixtures"""
self.scraper = WeatherScraper(
api_endpoint="https://api.test.com/weather"
)
self.mock_response = {
'current': {
'temp': 20,
'condition': {'text': 'Cloudy'},
'humidity': 65,
'wind_kph': 15,
},
'forecast': {
'forecastday': [
{
'date': '2024-01-01',
'day': {
'maxtemp_c': 25,
'mintemp_c': 15,
'condition': {'text': 'Sunny'},
'daily_chance_of_rain': 10,
}
}
]
}
}
@patch('requests.Session.get')
def test_fetch_weather_success(self, mock_get):
"""Test successful weather fetch"""
mock_response = MagicMock()
mock_response.json.return_value = self.mock_response
mock_get.return_value = mock_response
result = self.scraper.extract_weather_info('London')
self.assertIsNotNone(result)
self.assertEqual(result['location'], 'London')
self.assertEqual(result['current']['temperature'], 20)
@patch('requests.Session.get')
def test_fetch_weather_error(self, mock_get):
"""Test weather fetch with error"""
mock_get.side_effect = Exception("Connection error")
result = self.scraper.extract_weather_info('London')
self.assertIsNone(result)
def test_parse_forecast(self):
"""Test forecast parsing"""
forecast = self.scraper._parse_forecast(self.mock_response)
self.assertEqual(len(forecast), 1)
self.assertEqual(forecast[0]['date'], '2024-01-01')
self.assertEqual(forecast[0]['max_temp'], 25)
if __name__ == '__main__':
unittest.main()
Key Features
Feature Implementation API Discovery Selenium Wire captures network traffic Direct API Calls Bypasses DOM scraping, fetches JSON directly Caching SQLite with TTL support Rate Limiting Request throttling and backoff Error Handling Retry logic with exponential backoff Configuration Environment-based settings Testing Unit tests with mocks
This approach is faster, more reliable, and more maintainable than DOM scraping!
Show full message · 867 lines """
weather_api_fetcher.py
Fetch weather data directly from the discovered API endpoint
"""
import requests
import json
from typing import Dict, List, Optional
from datetime import datetime
import time
class WeatherAPIFetcher:
"""
Fetch weather data directly from the API endpoint
"""
def __init__(self, api_endpoint: str, headers: Optional[Dict] = None):
"""
Initialize fetcher with API endpoint
Args:
api_endpoint: The discovered API URL
headers: Custom headers (User-Agent, Authorization, etc.)
"""
self.api_endpoint = api_endpoint
self.session = requests.Session()
# Set default headers
self.headers = headers or {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
'Accept': 'application/json',
'Referer': 'https://weather.com/',
}
self.session.headers.update(self.headers)
def fetch_weather(self, location: str, unit: str = 'metric') -> Dict:
"""
Fetch weather data for a location
"""
params = {
'location': location,
'unit': unit,
}
try:
response = self.session.get(
self.api_endpoint,
params=params,
timeout=10
)
response.raise_for_status()
return response.json()
except requests.exceptions.RequestException as e:
print(f"Error fetching weather: {e}")
return None
def fetch_with_retry(self, location: str, max_retries: int = 3) -> Dict:
"""
Fetch with automatic retry on failure
"""
for attempt in range(max_retries):
try:
data = self.fetch_weather(location)
if data:
return data
except Exception as e:
print(f"Attempt {attempt + 1} failed: {e}")
if attempt < max_retries - 1:
time.sleep(2 ** attempt) # Exponential backoff
return None
class WeatherScraper:
"""
High-level weather scraper using discovered API
"""
def __init__(self, api_endpoint: str):
self.fetcher = WeatherAPIFetcher(api_endpoint)
def extract_weather_info(self, location: str) -> Dict:
"""
Extract and format weather information
"""
data = self.fetcher.fetch_weather(location)
if not data:
return None
# Parse response based on API structure
weather_info = {
'location': location,
'timestamp': datetime.now().isoformat(),
'current': self._parse_current(data),
'forecast': self._parse_forecast(data),
}
return weather_info
def _parse_current(self, data: Dict) -> Dict:
"""Parse current weather conditions"""
try:
# Adjust based on actual API response structure
current = data.get('current', {})
return {
'temperature': current.get('temp'),
'condition': current.get('condition', {}).get('text'),
'humidity': current.get('humidity'),
'wind_speed': current.get('wind_kph'),
'pressure': current.get('pressure_mb'),
'visibility': current.get('vis_km'),
}
except Exception as e:
print(f"Error parsing current weather: {e}")
return {}
def _parse_forecast(self, data: Dict) -> List[Dict]:
"""Parse forecast data"""
try:
forecasts = []
forecast_data = data.get('forecast', {}).get('forecastday', [])
for day in forecast_data[:5]: # Next 5 days
forecasts.append({
'date': day.get('date'),
'max_temp': day.get('day', {}).get('maxtemp_c'),
'min_temp': day.get('day', {}).get('mintemp_c'),
'condition': day.get('day', {}).get('condition', {}).get('text'),
'rain_chance': day.get('day', {}).get('daily_chance_of_rain'),
})
return forecasts
except Exception as e:
print(f"Error parsing forecast: {e}")
return []
# Example usage
if __name__ == "__main__":
# Use API endpoint discovered by Selenium Wire
API_ENDPOINT = "https://api.weatherapi.com/v1/current.json"
scraper = WeatherScraper(API_ENDPOINT)
locations = ['London', 'New York', 'Tokyo']
for location in locations:
print(f"\n{'='*60}")
print(f"Weather for {location}")
print('='*60)
weather = scraper.extract_weather_info(location)
if weather:
print(json.dumps(weather, indent=2))
"""
advanced_api_discovery.py
More sophisticated API discovery with detailed logging
"""
from seleniumwire import webdriver
from seleniumwire.utils import decode
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.chrome.service import Service
import json
import time
from urllib.parse import urlparse, parse_qs
class APIDiscoveryTool:
"""
Advanced tool for discovering and analyzing API endpoints
"""
def __init__(self, ignore_domains=None):
"""
Args:
ignore_domains: List of domains to ignore (e.g., analytics, ads)
"""
self.ignore_domains = ignore_domains or [
'google-analytics',
'facebook.com',
'doubleclick',
'mixpanel'
]
self.captured_apis = []
def is_ignored_domain(self, url: str) -> bool:
"""Check if domain should be ignored"""
return any(domain in url.lower() for domain in self.ignore_domains)
def extract_request_details(self, request) -> Dict:
"""Extract comprehensive request information"""
details = {
'url': request.url,
'method': request.method,
'headers': dict(request.headers),
'query_params': self._extract_query_params(request.url),
}
# Try to capture request body
if request.body:
try:
details['body'] = json.loads(request.body)
except:
details['body'] = request.body[:200] # First 200 chars
return details
def extract_response_details(self, request) -> Dict:
"""Extract response information"""
if not request.response:
return None
details = {
'status_code': request.response.status_code,
'headers': dict(request.response.headers),
'size': len(request.response.body) if request.response.body else 0,
}
# Try to parse JSON response
try:
body = decode(
request.response.body,
request.response.headers.get('Content-Encoding', 'identity')
)
details['data'] = json.loads(body)
except:
pass
return details
def _extract_query_params(self, url: str) -> Dict:
"""Extract query parameters from URL"""
parsed = urlparse(url)
return {k: v[0] if len(v) == 1 else v
for k, v in parse_qs(parsed.query).items()}
def discover_apis(self, url: str, wait_time: int = 10) -> List[Dict]:
"""
Discover all API endpoints on a page
"""
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument('--start-maximized')
chrome_options.add_argument('--disable-blink-features=AutomationControlled')
seleniumwire_options = {
'disable_encoding': True,
'verify_ssl': False,
}
driver = webdriver.Chrome(
service=Service(ChromeDriverManager().install()),
chrome_options=chrome_options,
seleniumwire_options=seleniumwire_options
)
try:
print(f"Loading {url}...")
driver.get(url)
# Wait for dynamic content to load
time.sleep(wait_time)
# Analyze all requests
for request in driver.requests:
if self.is_ignored_domain(request.url):
continue
# Look for JSON API endpoints
if request.response and 'application/json' in request.response.headers.get('Content-Type', ''):
api_info = {
'request': self.extract_request_details(request),
'response': self.extract_response_details(request),
'timestamp': time.time(),
}
self.captured_apis.append(api_info)
print(f"\n✓ Found API: {request.url}")
print(f" Method: {request.method}")
print(f" Status: {request.response.status_code}")
return self.captured_apis
finally:
driver.quit()
def export_apis(self, filename: str = 'discovered_apis.json'):
"""Export discovered APIs to JSON file"""
with open(filename, 'w') as f:
json.dump(self.captured_apis, f, indent=2, default=str)
print(f"\nExported {len(self.captured_apis)} APIs to {filename}")
if __name__ == "__main__":
tool = APIDiscoveryTool()
# Discover APIs
apis = tool.discover_apis(
'https://weather.com',
wait_time=10
)
# Export for analysis
tool.export_apis('weather_apis.json')
# Print summary
print(f"\n{'='*60}")
print(f"DISCOVERY SUMMARY")
print(f"{'='*60}")
print(f"Total APIs found: {len(apis)}")
"""
production_weather_scraper.py
Complete weather scraper with caching, rate limiting, and error handling
"""
import requests
import json
import sqlite3
from datetime import datetime, timedelta
from typing import Dict, Optional
import hashlib
from pathlib import Path
class CachedWeatherScraper:
"""
Weather scraper with caching and rate limiting
"""
def __init__(self, api_endpoint: str, cache_dir: str = './cache'):
self.api_endpoint = api_endpoint
self.cache_dir = Path(cache_dir)
self.cache_dir.mkdir(exist_ok=True)
# Initialize cache database
self.db_path = self.cache_dir / 'weather_cache.db'
self._init_cache_db()
# Rate limiting
self.request_count = 0
self.max_requests_per_minute = 60
self.last_request_time = {}
def _init_cache_db(self):
"""Initialize SQLite cache database"""
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
cursor.execute('''
CREATE TABLE IF NOT EXISTS weather_cache (
location_hash TEXT PRIMARY KEY,
location TEXT,
data JSON,
timestamp DATETIME,
expires_at DATETIME
)
''')
conn.commit()
conn.close()
def _get_cache_key(self, location: str) -> str:
"""Generate cache key"""
return hashlib.md5(location.lower().encode()).hexdigest()
def _check_rate_limit(self) -> bool:
"""Check if we're within rate limits"""
now = datetime.now()
if location := self.last_request_time.get('timestamp'):
if (now - datetime.fromisoformat(location)).total_seconds() < 60:
self.request_count += 1
if self.request_count > self.max_requests_per_minute:
return False
self.last_request_time['timestamp'] = now.isoformat()
return True
def get_cached_weather(self, location: str) -> Optional[Dict]:
"""Retrieve weather from cache if valid"""
cache_key = self._get_cache_key(location)
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
cursor.execute('''
SELECT data, expires_at FROM weather_cache
WHERE location_hash = ? AND expires_at > datetime('now')
''', (cache_key,))
result = cursor.fetchone()
conn.close()
if result:
data, _ = result
return json.loads(data)
return None
def cache_weather(self, location: str, data: Dict, ttl_hours: int = 6):
"""Cache weather data"""
cache_key = self._get_cache_key(location)
expires_at = datetime.now() + timedelta(hours=ttl_hours)
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
cursor.execute('''
INSERT OR REPLACE INTO weather_cache
(location_hash, location, data, timestamp, expires_at)
VALUES (?, ?, ?, datetime('now'), ?)
''', (cache_key, location, json.dumps(data), expires_at.isoformat()))
conn.commit()
conn.close()
def fetch_weather(self, location: str, use_cache: bool = True) -> Optional[Dict]:
"""
Fetch weather with caching support
"""
# Check cache first
if use_cache:
cached = self.get_cached_weather(location)
if cached:
print(f"✓ Cache hit for {location}")
return cached
# Check rate limit
if not self._check_rate_limit():
print("⚠ Rate limit exceeded")
return None
try:
print(f"⬇ Fetching weather for {location}...")
response = requests.get(
self.api_endpoint,
params={'q': location},
timeout=10
)
response.raise_for_status()
data = response.json()
# Cache the result
if use_cache:
self.cache_weather(location, data)
return data
except requests.exceptions.RequestException as e:
print(f"✗ Error fetching weather: {e}")
return None
def batch_fetch(self, locations: list) -> Dict:
"""
Fetch weather for multiple locations
"""
results = {}
for location in locations:
results[location] = self.fetch_weather(location)
# Small delay between requests
time.sleep(0.5)
return results
def clear_cache(self):
"""Clear expired cache entries"""
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
cursor.execute('''
DELETE FROM weather_cache WHERE expires_at < datetime('now')
''')
deleted = cursor.rowcount
conn.commit()
conn.close()
print(f"Cleared {deleted} expired cache entries")
# Usage example
if __name__ == "__main__":
import time
scraper = CachedWeatherScraper(
api_endpoint="https://api.weatherapi.com/v1/current.json",
cache_dir="./weather_cache"
)
locations = [
'London',
'New York',
'Tokyo',
'Sydney',
'Paris'
]
# Fetch batch of weather data
print("Fetching weather data...\n")
weather_data = scraper.batch_fetch(locations)
# Display results
for location, data in weather_data.items():
if data:
print(f"\n{location}: {data}")
else:
print(f"\n{location}: Failed to fetch")
# Clear expired cache
scraper.clear_cache()