Certainly! Below is a Python script that crawls a website and downloads all the images it finds. The script uses the requests library to handle HTTP requests, BeautifulSoup from the bs4 library to parse HTML content, and urllib to manage URLs.
Prerequisites
Before running the script, ensure you have the necessary Python packages installed. You can install them using pip:
bash
pip install requests beautifulsoup4
Script Explanation
Imports and Setup:
requests for making HTTP requests.
BeautifulSoup for parsing HTML content.
urljoin and urlparse from urllib.parse for handling and constructing URLs.
os for directory operations.
set to keep track of visited URLs and avoid cycles.
Functions:
is_valid(url): Checks if the URL is valid and uses HTTP or HTTPS.
get_all_images(base_url, soup): Extracts all image URLs from the page.
get_all_website_links(base_url, soup): Extracts all internal links to continue crawling.
download_image(img_url, folder_path): Downloads a single image.
crawl_website(start_url, max_pages=50): Orchestrates the crawling process, limiting to max_pages.
Main Execution:
Prompts the user for the starting URL.
Creates a directory named downloaded_images to store images.
Starts crawling and downloading images.
Complete Script
python
import requests
from bs4 import BeautifulSoup
from urllib.parse import urljoin, urlparse
import os
import sys
def is_valid(url):
"""
Checks whether `url` is a valid URL.
"""
parsed = urlparse(url)
return bool(parsed.netloc) and bool(parsed.scheme) and parsed.scheme in ['http', 'https']
def get_all_images(base_url, soup):
"""
Returns a set of all image URLs found on the page.
"""
img_urls = set()
for img in soup.find_all("img"):
img_url = img.get("src")
if not img_url:
# If img does not contain src attribute, skip
continue
# Resolve relative URLs
img_url = urljoin(base_url, img_url)
# Remove URL parameters
img_url = img_url.split("?")[0]
if is_valid(img_url):
img_urls.add(img_url)
return img_urls
def get_all_website_links(base_url, soup):
"""
Returns a set of all URLs found on the page that belong to the same domain.
"""
links = set()
for a_tag in soup.find_all("a"):
href = a_tag.get("href")
if href and href.startswith('/'):
href = urljoin(base_url, href)
elif href and not is_valid(href):
# Ignore invalid URLs
continue
if href and is_valid(href):
parsed_href = urlparse(href)
parsed_base = urlparse(base_url)
if parsed_href.netloc == parsed_base.netloc:
links.add(href)
return links
def download_image(img_url, folder_path):
"""
Downloads an image from `img_url` to the specified `folder_path`.
"""
try:
response = requests.get(img_url, stream=True, timeout=10)
response.raise_for_status() # Raise an error on bad status
except requests.RequestException as e:
print(f"Failed to download {img_url}: {e}")
return
# Extract image filename
path = urlparse(img_url).path
filename = os.path.basename(path)
if not filename:
filename = "image_" + str(hash(img_url)) + ".jpg" # Fallback filename
file_path = os.path.join(folder_path, filename)
# Avoid overwriting existing files
if os.path.exists(file_path):
print(f"Image already exists: {file_path}")
return
try:
with open(file_path, 'wb') as f:
for chunk in response.iter_content(1024):
f.write(chunk)
print(f"Downloaded: {img_url} to {file_path}")
except Exception as e:
print(f"Failed to save {img_url}: {e}")
def crawl_website(start_url, max_pages=50):
"""
Crawls the website starting from `start_url`, downloads all images, and
limits the crawl to `max_pages` to prevent infinite crawling.
"""
visited_pages = set()
pages_to_visit = set([start_url])
downloaded_images = set()
# Create a folder to save images
folder_path = "downloaded_images"
if not os.path.exists(folder_path):
os.makedirs(folder_path)
while pages_to_visit and len(visited_pages) < max_pages:
current_page = pages_to_visit.pop()
if current_page in visited_pages:
continue
print(f"Crawling: {current_page}")
try:
response = requests.get(current_page, timeout=10)
response.raise_for_status()
except requests.RequestException as e:
print(f"Failed to retrieve {current_page}: {e}")
continue
soup = BeautifulSoup(response.text, "html.parser")
# Extract and download images
img_urls = get_all_images(current_page, soup)
for img_url in img_urls:
if img_url not in downloaded_images:
download_image(img_url, folder_path)
downloaded_images.add(img_url)
visited_pages.add(current_page)
# Find new pages to visit
links = get_all_website_links(start_url, soup)
for link in links:
if link not in visited_pages and link not in pages_to_visit:
pages_to_visit.add(link)
print(f"Crawling finished. {len(downloaded_images)} images downloaded.")
if __name__ == "__main__":
if len(sys.argv) != 2:
print("Usage: python crawl_images.py <starting_url>")
sys.exit(1)
starting_url = sys.argv[1]
if not is_valid(starting_url):
print("Please provide a valid URL (including http:// or https://)")
sys.exit(1)
crawl_website(starting_url)
Usage Instructions
Save the Script:
Save the above script to a file named crawl_images.py.
Run the Script:
Open your terminal or command prompt, navigate to the directory containing crawl_images.py, and run:
bash
python crawl_images.py https://example.com
Replace https://example.com with the URL of the website you want to crawl.
Output:
The script will create a directory named downloaded_images in the current working directory.
All downloaded images will be saved in this folder.
The script will print logs indicating the progress of crawling and downloading.
Notes and Best Practices
Respect Website Policies:
Ensure that you have permission to crawl and download images from the target website. Check the website's robots.txt file and terms of service to understand their crawling policies.
Crawling Limit:
The max_pages parameter in the crawl_website function limits the number of pages to crawl (default is 50). Adjust this as needed to avoid overloading the target server.
Error Handling:
The script includes basic error handling to skip pages or images that cannot be retrieved. It logs errors to inform you of any issues encountered during the crawl.
Performance Considerations:
For large websites, crawling can be time-consuming and resource-intensive. Consider implementing additional features like multi-threading or asynchronous requests for improved performance, but be cautious to respect the target server's capacity.
Extending Functionality:
You can enhance the script by adding features such as:
Handling different image sources like CSS backgrounds.
Supporting other media types (e.g., videos).
Implementing rate limiting to prevent overwhelming the server.
Conclusion
This script provides a foundational approach to crawling a website and downloading all images found. Depending on your specific needs and the complexity of the target website, you might need to customize and extend the script further. Always ensure that your crawling activities comply with the website's policies and legal guidelines.