write me a python script to scrape chess.com for its piece images
- User
write me a python script to scrape chess.com for its piece images
Assistant
Here's a Python script to scrape Chess.com piece images. Note that you may need to adjust the
base_urlbased on the actual location of the images (you can inspect the website's network tab to find the correct URLs).import requests import os import time # Define the base URL where the images are hosted (may need adjustment) base_url = "https://secure.image棋.com/pieces/" # Example placeholder URL colors = ['white', 'black'] pieces = ['king', 'queen', 'rook', 'bishop', 'knight', 'pawn'] output_dir = 'chess_pieces' headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3' } def download_images(): if not os.path.exists(output_dir): os.makedirs(output_dir) for color in colors: for piece in pieces: filename = f"{color}_{piece}.png" url = f"{base_url}{filename}" try: response = requests.get(url, headers=headers, timeout=5) if response.status_code == 200: with open(os.path.join(output_dir, filename), 'wb') as f: f.write(response.content) print(f"Downloaded: {filename}") else: print(f"Failed {url} (Status {response.status_code})") except requests.exceptions.RequestException as e: print(f"Error: {e}") time.sleep(1) # Be polite to the server print("All downloads completed.") if __name__ == "__main__": download_images()Notes:
- Adjust the
base_url: You'll need to find the correct URL path by inspecting Chess.com's network traffic in your browser. - Check Robots.txt: Ensure Chess.com allows scraping (check
https://www.chess.com/robots.txt). - Error Handling: The script includes basic error handling but may need more robust checks.
- User-Agent: The headers mimic a browser to avoid being blocked.
- Rate Limiting: The
time.sleep(1)adds a 1-second delay between requests to be kind to the server.
How to Use:
- Run the script.
- Check the
chess_piecesdirectory for downloaded images. - If images aren't found, adjust the
base_urland filename patterns (e.g., trywK.png,bQ.png, etc.).
Example Adjustments:
If the actual URLs are like
https://secure.chess.com/pieces/white_king.png, set:base_url = "https://secure.chess.com/pieces/"If filenames use abbreviations (
wK,bQ), modify the loop:colors = ['w', 'b'] pieces = ['K', 'Q', 'R', 'B', 'N', 'P'] # ... and filename = f"{color}{piece}.png"- Adjust the
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.