Create a python app with a GUI that has Two input fields, one is called "Website URL" and the other "Save File", The purpose of the python app is to mass download images from websites specified in the first field
Assistant
Sure! Below is a Python application with a graphical user interface (GUI) that allows you to enter a website URL and specify a folder where you want to save the images. The application will download all images from the specified website.
Here's the step-by-step guide along with the complete code:
Python Image Downloader GUI Application
This application uses the following libraries:
tkinter: For creating the GUI.
requests: For making HTTP requests to fetch the web page and images.
BeautifulSoup: For parsing the HTML content and extracting image URLs.
os and urllib.parse: For handling file paths and URL manipulations.
Steps:
Import Necessary Libraries:
python
import tkinter as tk
from tkinter import filedialog, messagebox
import requests
from bs4 import BeautifulSoup
import os
from urllib.parse import urljoin, urlparse
Define the Function to Download Images:
python
def download_images():
url = url_entry.get()
save_folder = save_entry.get()
if not url:
messagebox.showerror("Error", "Please enter a website URL.")
return
if not save_folder:
messagebox.showerror("Error", "Please select a save folder.")
return
try:
response = requests.get(url)
if response.status_code != 200:
messagebox.showerror("Error", f"Failed to retrieve the URL. Status code: {response.status_code}")
return
soup = BeautifulSoup(response.content, 'html.parser')
images = soup.find_all('img')
if not images:
messagebox.showinfo("No Images", "No images found at the specified URL.")
return
os.makedirs(save_folder, exist_ok=True)
for img in images:
img_url = img.get('src')
if not img_url:
continue
img_url = urljoin(url, img_url)
# Get the image file name
img_name = os.path.basename(urlparse(img_url).path)
if not img_name:
img_name = 'image.jpg' # default name
try:
img_data = requests.get(img_url).content
img_path = os.path.join(save_folder, img_name)
with open(img_path, 'wb') as f:
f.write(img_data)
print(f"Downloaded {img_url} to {img_path}")
except Exception as e:
print(f"Failed to download {img_url}: {e}")
messagebox.showinfo("Finished", "Image download completed.")
except Exception as e:
messagebox.showerror("Error", f"An error occurred: {e}")
Explanation:
Retrieves the URL and save folder from the input fields.
Checks if the fields are not empty.
Fetches the web page content.
Parses the HTML to find all <img> tags.
For each image, constructs the absolute URL and downloads the image.
Creates labels and entry fields for "Website URL" and "Save Folder".
Adds a "Browse" button to select the save folder.
Adds a "Start Download" button to initiate the download process.
Runs the application's main event loop.
Complete Code:
python
import tkinter as tk
from tkinter import filedialog, messagebox
import requests
from bs4 import BeautifulSoup
import os
from urllib.parse import urljoin, urlparse
def download_images():
url = url_entry.get()
save_folder = save_entry.get()
if not url:
messagebox.showerror("Error", "Please enter a website URL.")
return
if not save_folder:
messagebox.showerror("Error", "Please select a save folder.")
return
try:
response = requests.get(url)
if response.status_code != 200:
messagebox.showerror("Error", f"Failed to retrieve the URL. Status code: {response.status_code}")
return
soup = BeautifulSoup(response.content, 'html.parser')
images = soup.find_all('img')
if not images:
messagebox.showinfo("No Images", "No images found at the specified URL.")
return
os.makedirs(save_folder, exist_ok=True)
for img in images:
img_url = img.get('src')
if not img_url:
continue
img_url = urljoin(url, img_url)
# Get the image file name
img_name = os.path.basename(urlparse(img_url).path)
if not img_name:
img_name = 'image.jpg' # default name
try:
img_data = requests.get(img_url).content
img_path = os.path.join(save_folder, img_name)
with open(img_path, 'wb') as f:
f.write(img_data)
print(f"Downloaded {img_url} to {img_path}")
except Exception as e:
print(f"Failed to download {img_url}: {e}")
messagebox.showinfo("Finished", "Image download completed.")
except Exception as e:
messagebox.showerror("Error", f"An error occurred: {e}")
def browse_folder():
folder_selected = filedialog.askdirectory()
save_entry.delete(0, tk.END)
save_entry.insert(0, folder_selected)
root = tk.Tk()
root.title("Image Downloader")
# Website URL input
url_label = tk.Label(root, text="Website URL:")
url_label.grid(row=0, column=0, padx=10, pady=10, sticky='e')
url_entry = tk.Entry(root, width=50)
url_entry.grid(row=0, column=1, padx=10, pady=10)
# Save Folder input
save_label = tk.Label(root, text="Save Folder:")
save_label.grid(row=1, column=0, padx=10, pady=10, sticky='e')
save_entry = tk.Entry(root, width=50)
save_entry.grid(row=1, column=1, padx=10, pady=10)
browse_button = tk.Button(root, text="Browse", command=browse_folder)
browse_button.grid(row=1, column=2, padx=10, pady=10)
# Download button
download_button = tk.Button(root, text="Start Download", command=download_images)
download_button.grid(row=2, column=1, padx=10, pady=20)
root.mainloop()
How to Run the Application:
Install Required Libraries:
Make sure you have the required libraries installed. You can install them using pip:
bash
pip install requests beautifulsoup4
Save the Script:
Save the Python script to a file, for example, image_downloader.py.
Run the Script:
Run the script using Python:
bash
python image_downloader.py
Use the Application:
Enter the website URL from which you want to download images.
Click the "Browse" button to select a folder where you want to save the images.
Click "Start Download" to begin downloading the images.
Notes:
Error Handling:
The application includes error handling to manage situations such as invalid URLs, no images found, and network errors.
Image URLs:
The script handles both absolute and relative image URLs by using urljoin to construct the full URL.
Saving Images:
Images are saved with their original filenames. If an image doesn't have a valid name, a default name image.jpg is used.
Output Messages:
The application uses message boxes to inform you of the progress and any errors.
Console Output:
The script also prints messages in the console for each downloaded image, which can be useful for debugging.
Customization:
Supported Image Formats:
Currently, the script does not filter image formats. You can modify it to download only specific image formats, such as .jpg, .png, etc.
Concurrency:
For a large number of images, you might want to download images concurrently. This can be achieved using threading or asynchronous requests.
Improved UI:
You can enhance the GUI with additional features, such as a progress bar or options to set download limits.
Disclaimer:
Respect Website Policies:
Make sure to respect the website's terms of service and robots.txt file. Do not use this script to download images from websites where it is not permitted.
Use Responsibly:
Avoid overloading websites with too many requests in a short period. Consider adding delays between requests if necessary.
Let me know if you need further assistance or modifications to the application!