使用Python3.5与Requests下载Openi图片:是否需逐个下载?
如何从Openi平台批量下载图片?
Hey there! Let's tackle this question for you.
First off: Yes, you do need to download each image individually — the Openi REST API you're calling only returns metadata (like the .png filenames) rather than providing a bulk download option. But don't worry, we can automate this process with Python so you don't have to do it manually.
Here's a step-by-step solution:
- Fetch the image metadata using the
retrieve.phpendpoint (you already have this part covered) - Parse the returned JSON to extract each image's filename
- Build the direct download URL for each image and save them locally
Full example code
import requests import json import time # For adding delays if needed # Fetch metadata for your query response = requests.get( "http://openi.nlm.nih.gov/retrieve.php", params={"query": "Feulgen", "m": 1, "n": 12} ) if response.status_code == 200: try: image_data = json.loads(response.content) # Loop through each image entry in the metadata for img_entry in image_data.get("list", []): img_filename = img_entry.get("imgFileName") if not img_filename: print("Skipping entry: No image filename found") continue # Construct the direct image URL img_url = f"http://openi.nlm.nih.gov/images/{img_filename}" img_response = requests.get(img_url) if img_response.status_code == 200: # Save the image to your local machine with open(img_filename, "wb") as img_file: img_file.write(img_response.content) print(f"Successfully downloaded: {img_filename}") # Optional: Add a small delay to be kind to the server time.sleep(0.5) else: print(f"Failed to download {img_filename}: Status code {img_response.status_code}") except json.JSONDecodeError: print("Error parsing JSON response from the API") else: print(f"Failed to fetch metadata: Status code {response.status_code}")
A few quick tips:
- Handle exceptions: The code above includes basic error handling for JSON parsing and missing filenames, but you can expand this to cover network timeouts or other issues
- Respect rate limits: Adding a small delay (like
time.sleep(0.5)) between requests helps avoid overwhelming the server and getting your IP blocked - Customize save paths: Instead of saving to the current directory, you can create a dedicated folder (e.g.,
./openi_images/) and save images there — just make sure the folder exists before running the code
内容的提问来源于stack exchange,提问作者MissBleu
相关产品推荐
相关产品推荐

