from flask import Flask, Response, request, abort, render_template_string import requests from bs4 import BeautifulSoup from urllib.parse import urljoin, urlparse import os app = Flask(__name__) # Function to create download directory if it doesn't exist def create_download_directory(): if not os.path.exists('downloads'): os.makedirs('downloads') # Function to download content and replace links def download_and_replace_links(url): try: response = requests.get(url) response.raise_for_status() # Check if the request was successful except requests.RequestException as e: return f"Error fetching the URL: {e}" soup = BeautifulSoup(response.text, 'html.parser') create_download_directory() for tag in soup.find_all(['link', 'img', 'script']): url_attr = 'href' if tag.name == 'link' else 'src' if tag.has_attr(url_attr): resource_url = tag[url_attr] if resource_url.startswith(('http', 'https')): try: filename = os.path.basename(urlparse(resource_url).path) filepath = os.path.join('downloads', filename) if not os.path.exists(filepath): # Avoid re-downloading existing files resource_response = requests.get(resource_url) resource_response.raise_for_status() with open(filepath, 'wb') as f: f.write(resource_response.content) tag[url_attr] = urljoin('/downloads/', filename) except requests.RequestException as e: print(f"Error downloading {resource_url}: {e}") return str(soup) # Flask route to serve index page @app.route('/') def index(): return render_template_string('''
To use the proxy, append the URL parameter like this:
/proxy?url=http://example.com