import os import requests # Set up directories output_dir = "mtg_images" # Folder where images will be saved if not os.path.exists(output_dir): os.makedirs(output_dir) # Function to fetch all cards from Scryfall API and save images def fetch_all_cards(): url = "https://api.scryfall.com/cards/search?q=lang%3Aen" while url: # Fetch a page of cards response = requests.get(url) data = response.json() # Process each card in the current page for card in data['data']: card_name = card['name'].replace('/', '_') # Avoid slashes in filenames # Check if the card has image_uris field if 'image_uris' in card: image_url = card['image_uris']['large'] # Use the "large" image for good quality image_extension = ".jpg" image_filename = f"{card_name}{image_extension}" image_path = os.path.join(output_dir, image_filename) # Check if the image already exists to avoid re-downloading if not os.path.exists(image_path): print(f"Downloading {card_name}...") try: # Download and save the image image_data = requests.get(image_url).content with open(image_path, 'wb') as img_file: img_file.write(image_data) except Exception as e: print(f"Failed to download {card_name}: {e}") else: print(f"{card_name} already downloaded!") else: print(f"No image found for {card['name']}") # Move to the next page of results url = data.get('next_page') # Start downloading if __name__ == "__main__": print("Starting card image download...") fetch_all_cards() print("Download complete!")