[python]图片批量下载V1.0
app.py
#from flask import Flask, request, render_template, redirect, url_for, flash
#import os
#import requests
#from bs4 import BeautifulSoup
#from urllib.parse import urljoin
#import sys
#
#
#app = Flask(__name__)
#app.secret_key = 'your_secret_key' # 必须设置密钥用于闪烁消息
#
#
#
#def fetch_and_save_images(url, save_dir='images'):
# if not os.path.exists(save_dir):
# os.makedirs(save_dir)
#
# headers = {
# 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
# }
#
# try:
# response = requests.get(url, headers=headers, timeout=10)
# response.raise_for_status()
#
# soup = BeautifulSoup(response.text, 'html.parser')
# images = soup.find_all('img')
#
# for index, img in enumerate(images):
# img_url = img.get('src')
# if img_url:
# img_url = urljoin(url, img_url)
# img_extension = os.path.splitext(img_url)[1].lower()
#
# if img_extension not in ['.jpg', '.jpeg', '.png', '.gif']:
# continue
#
# img_name = f'image_{index+1}{img_extension}'
# img_path = os.path.join(save_dir, img_name)
#
# try:
# img_response = requests.get(img_url, headers=headers, stream=True, timeout=10)
# img_response.raise_for_status()
#
# with open(img_path, 'wb') as file:
# for chunk in img_response.iter_content(chunk_size=8192):
# file.write(chunk)
#
# except requests.RequestException as e:
# print(f"Error downloading image {img_url}: {e}")
#
# except requests.RequestException as e:
# print(f"Request error: {e}")
#
#@app.route('/', methods=['GET', 'POST'])
#def index():
# if request.method == 'POST':
# url = request.form.get('url')
# if not url:
# flash('URL is required!')
# return redirect(url_for('index'))
#
# fetch_and_save_images(url)
# flash('Images have been saved successfully!')
# return redirect(url_for('index'))
#
# return render_template('index.html')
#
#if __name__ == '__main__':
# app.run(debug=True)
#
mkdir templates
cd templates
vi index.html
#
#<!DOCTYPE html>
#<html lang="en">
#<head>
# <meta charset="UTF-8">
# <meta name="viewport" content="width=device-width, initial-scale=1.0">
# <title>Image Downloader</title>
#</head>
#<body>
# <h1>Image Downloader</h1>
# <form method="post">
# <label for="url">Enter URL:</label>
# <input type="text" id="url" name="url" required>
# <button type="submit">Download Images</button>
# </form>
# {% with messages = get_flashed_messages() %}
# {% if messages %}
# <ul>
# {% for message in messages %}
# <li>{{ message }}</li>
# {% endfor %}
# </ul>
# {% endif %}
# {% endwith %}
#</body>
#</html>
#