"""
Python script to scrape data from a dynamic website using Selenium.
This example scrapes quotes from https://quotes.toscrape.com/js/, a demo site
designed for scraping practice that loads content dynamically via JavaScript.
Requirements:
- pip install selenium webdriver-manager
Note: Always respect robots.txt, terms of service, and rate limits when scraping.
This is for educational purposes.
"""
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
import time
import csv
def scrape_quotes():
# Set up the Chrome driver (automatically downloads the latest version)
service = Service(ChromeDriverManager().install())
options = webdriver.ChromeOptions()
options.add_argument('--headless') # Run in headless mode (no browser UI)
options.add_argument('--no-sandbox')
options.add_argument('--disable-dev-shm-usage')
driver = webdriver.Chrome(service=service, options=options)
try:
# Navigate to the dynamic quotes page
url = 'https://quotes.toscrape.com/js/'
driver.get(url)
# Wait for the quotes to load dynamically (up to 10 seconds)
wait = WebDriverWait(driver, 10)
quote_elements = wait.until(
EC.presence_of_all_elements_located((By.CSS_SELECTOR, '.quote'))
)
quotes_data = []
for quote in quote_elements:
# Extract quote text
text = quote.find_element(By.CSS_SELECTOR, 'span.text').text
# Extract author
author = quote.find_element(By.CSS_SELECTOR, 'small.author').text
# Extract tags (if any)
tags = [tag.text for tag in quote.find_elements(By.CSS_SELECTOR, '.tag')]
quotes_data.append({
'quote': text,
'author': author,
'tags': ', '.join(tags)
})
# Print scraped data
for data in quotes_data:
print(f"Quote: {data['quote']}")
print(f"Author: {data['author']}")
print(f"Tags: {data['tags']}")
print('-' * 50)
# Optionally save to CSV
save_to_csv(quotes_data)
return quotes_data
except Exception as e:
print(f"Error during scraping: {e}")
return []
finally:
# Always close the browser
driver.quit()
def save_to_csv(data, filename='quotes.csv'):
"""Save scraped data to a CSV file."""
if data:
with open(filename, 'w', newline='', encoding='utf-8') as file:
writer = csv.DictWriter(file, fieldnames=['quote', 'author', 'tags'])
writer.writeheader()
writer.writerows(data)
print(f"\nData saved to {filename}")
if __name__ == "__main__":
quotes = scrape_quotes()
print(f"\nTotal quotes scraped: {len(quotes)}")
How to Run:
- Install dependencies:
pip install selenium webdriver-manager
- Run the script:
python scrape_quotes.py
Key Features:
- Dynamic Handling: Uses
WebDriverWait to wait for JavaScript-loaded elements.
- Headless Mode: Runs without opening a visible browser.
- Error Handling: Catches exceptions and ensures browser closes.
- Output: Prints data to console and saves to
quotes.csv.
- Customizable: Easily adapt selectors for other sites (inspect elements with DevTools).
Pro Tip: For production, add delays (time.sleep(2)) between actions to mimic human behavior and avoid bans. Replace the URL and selectors for your target site!