I'll provide you with a complete solution for scraping Forex Factory data using Python with Selenium, which is the recommended approach based on current website structure. This solution includes both the Python script and a simple HTML template to display the reformatted data.
Python Script for Scraping (save as forex_scraper.py)
python
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from webdriver_manager.chrome import ChromeDriverManager
import pandas as pd
import time
import json
from datetime import datetime
import os
def scrape_forex_factory(url="https://www.forexfactory.com/calendar", output_file="forex_data.json"):
# Set up Chrome options
chrome_options = Options()
chrome_options.add_argument("--headless") # Run in headless mode
chrome_options.add_argument("--no-sandbox")
chrome_options.add_argument("--disable-dev-shm-usage")
# Initialize the Chrome driver
driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()), options=chrome_options)
try:
# Navigate to Forex Factory
print(f"Navigating to {url}...")
driver.get(url)
# Wait for the calendar to load
wait = WebDriverWait(driver, 20)
wait.until(EC.presence_of_element_located((By.CLASS_NAME, "calendar__table")))
# Scroll down to load all events
print("Scrolling to load all events...")
last_height = driver.execute_script("return document.body.scrollHeight")
while True:
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
time.sleep(2) # Wait for page to load
new_height = driver.execute_script("return document.body.scrollHeight")
if new_height == last_height:
break
last_height = new_height
# Find all calendar rows
print("Extracting event data...")
rows = driver.find_elements(By.CSS_SELECTOR, ".calendar__row.calendar_row")
# Initialize data list
forex_data = []
# Extract data from each row
for row in rows:
try:
# Extract basic information
date_cell = row.find_element(By.CSS_SELECTOR, ".calendar__date").text.strip() if row.find_elements(By.CSS_SELECTOR, ".calendar__date") else ""
time_cell = row.find_element(By.CSS_SELECTOR, ".calendar__time").text.strip() if row.find_elements(By.CSS_SELECTOR, ".calendar__time") else ""
currency = row.find_element(By.CSS_SELECTOR, ".calendar__currency").text.strip() if row.find_elements(By.CSS_SELECTOR, ".calendar__currency") else ""
# Extract event details
event = row.find_element(By.CSS_SELECTOR, ".calendar__event").text.strip() if row.find_elements(By.CSS_SELECTOR, ".calendar__event") else ""
# Extract impact (requires special handling for the colored icons)
impact_element = row.find_elements(By.CSS_SELECTOR, ".calendar__impact")
impact = ""
if impact_element:
# Check for the colored impact indicator
if row.find_elements(By.CSS_SELECTOR, ".icon--ff-impact-high"):
impact = "High"
elif row.find_elements(By.CSS_SELECTOR, ".icon--ff-impact-medium"):
impact = "Medium"
elif row.find_elements(By.CSS_SELECTOR, ".icon--ff-impact-low"):
impact = "Low"
else:
impact = "None"
# Extract actual, forecast, and previous values
actual = row.find_element(By.CSS_SELECTOR, ".calendar__actual").text.strip() if row.find_elements(By.CSS_SELECTOR, ".calendar__actual") else ""
forecast = row.find_element(By.CSS_SELECTOR, ".calendar__forecast").text.strip() if row.find_elements(By.CSS_SELECTOR, ".calendar__forecast") else ""
previous = row.find_element(By.CSS_SELECTOR, ".calendar__previous").text.strip() if row.find_elements(By.CSS_SELECTOR, ".calendar__previous") else ""
# Create event data dictionary
event_data = {
"date": date_cell,
"time": time_cell,
"currency": currency,
"event": event,
"impact": impact,
"actual": actual,
"forecast": forecast,
"previous": previous
}
# Add to data list
forex_data.append(event_data)
except Exception as e:
print(f"Error processing row: {e}")
continue
# Save data to JSON file
with open(output_file, 'w', encoding='utf-8') as f:
json.dump(forex_data, f, ensure_ascii=False, indent=4)
print(f"Data saved to {output_file}")
# Convert to DataFrame and save as CSV as well
df = pd.DataFrame(forex_data)
csv_file = output_file.replace('.json', '.csv')
df.to_csv(csv_file, index=False)
print(f"Data also saved to {csv_file}")
return forex_data
except Exception as e:
print(f"An error occurred: {e}")
return []
finally:
# Close the browser
driver.quit()
if __name__ == "__main__":
# Get current date for the filename
current_date = datetime.now().strftime("%Y%m%d")
output_file = f"forex_data_{current_date}.json"
# Run the scraper
scrape_forex_factory(output_file=output_file)
HTML Template (save as forex_display.html)
html
Setup and Usage Instructions
Install required packages:
bash
pip install selenium pandas webdriver-manager
Run the Python script to scrape data:
bash
python forex_scraper.py
This will create JSON and CSV files with the scraped data.
Open the HTML file:
Place both the Python script and HTML file in the same directory
After running the Python script, open the HTML file in a web browser
The data will be displayed in a formatted table with filtering options
Key Features
Data Collection:
Scrapes date, time, currency, event name, impact level, and actual/forecast/previous values
Properly handles the impact icons which display as colored indicators on ForexFactory
Scrolls through the page to ensure all events are loaded
HTML Display:
Clean, responsive design for easy viewing
Filter by currency or impact level
Color-coding for impact levels (high, medium, low)
Easy refresh functionality
Data Export:
Saves data in both JSON and CSV formats
File names include the current date for easy tracking
Important Notes
This solution uses Selenium because ForexFactory implements Cloudflare protection that prevents basic scraping methods[1][10].
The website structure may change over time, requiring updates to the selectors used in the script[1].
Be aware of ForexFactory's terms of service regarding automated data collection. Consider checking their robots.txt file before extensive scraping[5].
For historical data going back several years, you might want to modify the script to iterate through different date ranges or consider using already compiled datasets[2].
Time zone settings are important for accurate data interpretation. The script captures the time as displayed on the website based on your browser settings[6][10].