Python从URL文本文件下载图片:下载至25个后停止问题
Fixing Your Batch Image Download Stopping at the 25th Item
Hey there! The issue with your code halting after the 25th download boils down to how you’ve structured your try-except block. Right now, you’ve wrapped the entire download loop inside the try block—so if any single link fails (like a timeout, broken URL, or permission error), the exception triggers, hits the pass, and exits the loop entirely. That’s why it stops abruptly!
Let’s rewrite the code to fix this, plus add some improvements to make it more robust:
import urllib.request import socket # Set timeout for requests socket.setdefaulttimeout(30) # Use `with` to auto-manage file closure (no need for manual f.close()) with open('urls.txt', 'r') as f: # Clean up each link properly (removes newlines, spaces, tabs) links = [line.strip() for line in f.readlines()] total_links = len(links) print(f"Total links to download: {total_links}") download_count = 0 for idx, link in enumerate(links): try: # Download the image, use download_count for sequential filenames urllib.request.urlretrieve(link, f'dosa\\{download_count + 1}.jpg') download_count += 1 print(f"Successfully downloaded {download_count}.jpg") except Exception as e: # Don't ignore failures—log the error to debug later print(f"Failed to download link {idx + 1}: {link}") print(f"Error details: {str(e)}") print(f"Download complete! Successfully got {download_count} out of {total_links} images.")
Key Changes Explained:
- Per-link exception handling: The
try-exceptis now inside the loop. If one link fails, the code logs the issue and moves straight to the next link instead of stopping the entire batch. withstatement for files: This ensures the file is closed automatically, even if an error occurs during processing—no risk of leaving files open accidentally.- Better link cleaning:
line.strip()removes all leading/trailing whitespace (including newlines, spaces, or tabs) instead of just chopping off the last character with[:-1](which can break links that don’t end with a newline). - Error logging: Instead of silently ignoring failures, we print the problematic link and error message. This lets you check exactly why the 25th link failed (maybe it’s broken, timed out, or requires authentication).
Bonus Tips:
- If you’re downloading many images, add a small delay between requests (using
time.sleep(1)) to avoid hitting server rate limits. - For more reliable downloads, consider switching to the
requestslibrary—it’s more user-friendly and handles edge cases like redirects or authentication better thanurllib.
内容的提问来源于stack exchange,提问作者Mohneesh S
相关产品推荐
相关产品推荐

