from bs4 import BeautifulSoup # Read the original HTML with open("index.html", "r", encoding="utf-8") as f: html = f.read() # Parse HTML soup = BeautifulSoup(html, "html.parser") # Find all inline scripts (no src attribute) inline_scripts = soup.find_all("script", src=False) # Extract JS code all_js = "\n\n".join(script.string or "" for script in inline_scripts) # Remove inline script tags from HTML for script in inline_scripts: script.decompose() # Insert new external script reference new_script_tag = soup.new_tag("script", src="script.js") soup.body.append(new_script_tag) # Write updated HTML back with open("index.html", "w", encoding="utf-8") as f: f.write(str(soup)) # Write JS to external file with open("script.js", "w", encoding="utf-8") as f: f.write(all_js) print("✅ Inline JavaScript extracted to script.js and index.html updated.")