You have an HTML file — a saved page, an old export, a backup — and the images do not display because the site it came from is gone. Whether you can recover them depends on how they were referenced. This guide covers finding every image reference, extracting the ones embedded in the file itself, and retrieving the rest from web archives.
Step 1: find every reference#
Images hide in more places than the obvious src attribute:
<img src="/images/photo.jpg">
<img srcset="small.jpg 480w, large.jpg 1200w">
<img data-src="/images/lazy.jpg"> <!-- lazy loading -->
<source srcset="photo.webp" type="image/webp">
<div style="background-image: url('/bg.jpg')">
<meta property="og:image" content="/share.png">
A script that catches all of them:
import re
from pathlib import Path
from html.parser import HTMLParser
class ImageFinder(HTMLParser):
def __init__(self):
super().__init__()
self.urls = set()
def handle_starttag(self, tag, attrs):
attributes = dict(attrs)
for key in ("src", "data-src", "data-original", "content", "href"):
value = attributes.get(key)
if value and re.search(r"\.(jpe?g|png|gif|webp|svg|avif)", value, re.I):
self.urls.add(value)
for key in ("srcset", "data-srcset"):
value = attributes.get(key)
if value:
for part in value.split(","):
url = part.strip().split(" ")[0]
if url:
self.urls.add(url)
style = attributes.get("style", "")
self.urls.update(re.findall(r"url\(['\"]?([^'\")]+)", style))
html = Path("page.html").read_text(encoding="utf-8", errors="replace")
finder = ImageFinder()
finder.feed(html)
for url in sorted(finder.urls):
print(url)
Do not forget the stylesheet. Background images referenced from CSS will not appear in the HTML at all:
grep -oE "url\([^)]+\)" styles.css | sort -u
Step 2: check for embedded images first#
Some images are inside the file already, encoded as data URIs. These need no network and are the easiest to recover:
import base64
import re
from pathlib import Path
html = Path("page.html").read_text(encoding="utf-8", errors="replace")
output = Path("recovered")
output.mkdir(exist_ok=True)
pattern = re.compile(r"data:image/(?P<ext>\w+);base64,(?P<data>[A-Za-z0-9+/=]+)")
for i, match in enumerate(pattern.finditer(html), 1):
extension = match.group("ext").replace("jpeg", "jpg").replace("svg+xml", "svg")
try:
raw = base64.b64decode(match.group("data"))
except Exception:
print(f"image {i}: could not decode")
continue
path = output / f"embedded-{i:03d}.{extension}"
path.write_bytes(raw)
print(f"wrote {path} ({len(raw):,} bytes)")
Inline SVG is even simpler — it is already text in the file, so you can cut each <svg> element straight out into its own .svg.
Step 3: look for a saved-page folder#
If the file came from a browser’s Save Page As, the images are probably already on disk:
page.html
page_files/ <- Chrome and Edge
page-Dateien/ <- localised names vary
ls -R page_files/ | head -50
An MHTML or .mht file bundles everything into one file, and Python can unpack it:
import email
from pathlib import Path
message = email.message_from_bytes(Path("page.mht").read_bytes())
output = Path("recovered")
output.mkdir(exist_ok=True)
for i, part in enumerate(message.walk()):
if part.get_content_maintype() != "image":
continue
payload = part.get_payload(decode=True)
name = Path(part.get("Content-Location", f"image-{i}")).name or f"image-{i}"
(output / name).write_bytes(payload)
print("wrote", name)
Step 4: try the archives#
For images that were referenced but never stored locally, the Wayback Machine is the main hope.
import requests
from pathlib import Path
from urllib.parse import urljoin, urlparse
import time
BASE = "https://oldsite.example.com/" # the original site
OUTPUT = Path("recovered")
OUTPUT.mkdir(exist_ok=True)
def wayback_url(url):
"""Ask the availability API for the nearest archived copy."""
response = requests.get(
"https://archive.org/wayback/available",
params={"url": url},
timeout=15,
)
data = response.json()
snapshot = data.get("archived_snapshots", {}).get("closest")
return snapshot["url"] if snapshot and snapshot.get("available") else None
def recover(relative_url):
absolute = urljoin(BASE, relative_url)
name = Path(urlparse(absolute).path).name or "image"
archived = wayback_url(absolute)
if not archived:
print("not archived:", absolute)
return False
# id_ asks for the original bytes, without the archive's toolbar
direct = archived.replace("/http", "id_/http", 1)
response = requests.get(direct, timeout=30)
if response.status_code != 200 or not response.content:
print("failed:", absolute)
return False
(OUTPUT / name).write_bytes(response.content)
print("recovered:", name, f"({len(response.content):,} bytes)")
return True
for url in sorted(finder.urls):
if url.startswith("data:"):
continue
recover(url)
time.sleep(1) # be polite to a free service
To see everything the archive has for a domain, the CDX API lists it:
curl "http://web.archive.org/cdx/search/cdx?url=oldsite.example.com/*&output=text&fl=original&collapse=urlkey&filter=mimetype:image/.*&limit=500"
That often finds images the HTML never referenced — older versions, or files from pages you do not have.
Step 5: rewrite the HTML#
Once the files are recovered, point the page at them:
import re
from pathlib import Path
from urllib.parse import urlparse
html = Path("page.html").read_text(encoding="utf-8", errors="replace")
recovered = {p.name for p in Path("recovered").iterdir() if p.is_file()}
def rewrite(match):
attribute, url = match.group(1), match.group(2)
name = Path(urlparse(url).path).name
if name in recovered:
return f'{attribute}="recovered/{name}"'
return match.group(0)
html = re.sub(r'(src|data-src|href)="([^"]+)"', rewrite, html)
Path("page-fixed.html").write_text(html, encoding="utf-8")
print("wrote page-fixed.html")
Open the result and check the browser console — any remaining 404s tell you exactly what is still missing.
Other places to look#
- Your browser cache. If you viewed the page recently, the images may still be there. Chrome and Firefox both have cache viewer extensions.
- Search engine caches. Occasionally hold a copy after the site is gone.
- Image search by URL. Reverse image search sometimes finds the same file elsewhere.
- Other archives. archive.today and, for some domains, national web archives.
- The original author. Worth an email before spending an afternoon on scripts.
Verifying what you got#
from pathlib import Path
SIGNATURES = {
b"\xff\xd8\xff": "jpg",
b"\x89PNG": "png",
b"GIF8": "gif",
b"RIFF": "webp",
b"<svg": "svg",
b"<?xml": "svg",
}
for path in Path("recovered").iterdir():
head = path.read_bytes()[:8]
kind = next((v for k, v in SIGNATURES.items() if head.startswith(k)), None)
if kind is None:
print("NOT AN IMAGE:", path.name, head[:8])
elif not path.suffix.lower().lstrip(".").startswith(kind[:3]):
print("extension mismatch:", path.name, "looks like", kind)
Archives sometimes return an HTML error page with a 200 status, which lands on disk as a .jpg containing HTML. Checking the first few bytes catches those immediately.
Questions people ask#
Can I recover images if the file only has relative URLs?
You need to know the original domain to rebuild the absolute URLs. Check the page for a canonical link, an og:url meta tag, or any absolute link in the markup.
What if the site was never archived?
Then the archives cannot help. Try the browser cache, search engine caches, and reverse image search. Failing all of those, contact whoever ran the site.
Why do the recovered images look wrong?
Check the first bytes as above. A file that is really an HTML error page, or a placeholder the archive served instead of the original, is the usual explanation.
Is scraping the Wayback Machine allowed?
It is a free public service. Rate-limit yourself — one request a second is reasonable — and do not run a large recovery job in parallel.
Where to go next#
- Web scraping and automation — the requests and parsing used here.
- Python file handling — writing binary files correctly.
- Getting a file name from a path — the URL parsing above.