To get a website’s favicon from its URL, fetch the page, inspect its HTML for icon-related <link> elements, resolve each href against the page URL, then retrieve the selected image. If the page declares no icon, try the conventional /favicon.ico path at the site root—but treat it as a fallback, not a guarantee.
For an API you build, the important design choice is whether to return one selected icon or all declared candidates and their metadata. Favicon extraction also answers a different question from whether Google displays that icon in Search results.
How favicon extraction from a webpage URL works
A favicon extractor is a small crawler with two distinct jobs: discover which icon resources a page declares, then retrieve one or more of those resources. The usual first step is to request the HTML document and parse its <head> for <link> elements whose rel value identifies an icon.
Google Search Central documents rel="icon", the historical rel="shortcut icon", and Apple-specific apple-touch-icon and apple-touch-icon-precomposed values. The href may be a relative or absolute URL, and the file may be hosted on a different domain or CDN. See Google’s favicon guidance and MDN’s documentation of the rel attribute.
Quick wins for a faster PC:
Clear out junk files and repair common Windows errorsFree Scan →Scan for outdated or missing drivers - takes under a minuteDriver Scan →Repair Windows errors before they cause bigger problemsFix Now →#1 Best Overall
- USB-C 2-in-1 storage OTG: The Lexar JumpDrive Dual Drive D40E features USB Type-A and Type-C connectors in a slim, portable form factor for easy device compatibility
- Transfer speeds up to 100MB/s: Based on internal testing, performance may vary depending upon the host device, interface, and usage conditions. 1MB=1,000,000 bytes
- Plug and Play: Widely compatible with USB Type-C smartphones, tablets, laptops, Macs, and traditional Type-A devices, no software installation required. The 360° swivel design allows for easy switching between connectors without the hassle of losing a cap
- Durable & Compact: The Lexar D40E USB memory stick features a metal enclosure, withstands temperatures from 0° to 50° C (32°F to 122°F), and is lightweight at 26g with dimensions of 70.4 x 16.9 x 11.7mm
- Security & Warranty: Securely protects files using an advanced security software solution with 256-bit AES encryption. Backed by a Lexar 3-year limited warranty
- Request the page URL and retain the final URL after redirects.
- Parse the returned HTML for icon-related links; record each link’s
rel,href,type,sizes, andmedia, when present. - Resolve relative
hrefvalues against the final document URL, not just the original URL string. - Select a candidate according to the intended use, then request that icon resource separately.
- If no declared candidate is available, consider trying the site-root
/favicon.icopath.
Resolving relative icon URLs correctly
Suppose the document URL is https://example.com/products/page and its HTML contains <link rel="icon" href="../assets/site.png">. Resolve that reference with a URL resolver against the document URL; do not simply concatenate strings. The resolved resource is https://example.com/assets/site.png. A root-relative reference such as /icons/site.png resolves from the origin, while an absolute URL may point to a CDN.
Redirects matter too: a relative reference should be interpreted in the context of the final document URL returned by the request. Keep that final URL available in your parser so a redirect to another path or host does not produce an incorrect icon address.
Which icon should an API return?
A page can declare multiple icon candidates for different sizes, formats, or display conditions. Browsers use attributes such as media, type, and sizes when choosing among them, and may move to another candidate if a selected resource is unsuitable. MDN describes this selection behavior in its guide to webpage metadata.
Rank #2
- High-speed USB 3.0 performance of up to 150MB/s(1) [(1) Write to drive up to 15x faster than standard USB 2.0 drives (4MB/s); varies by drive capacity. Up to 150MB/s read speed. USB 3.0 port required. Based on internal testing; performance may be lower depending on host device, usage conditions, and other factors; 1MB=1,000,000 bytes]
- Transfer a full-length movie in less than 30 seconds(2) [(2) Based on 1.2GB MPEG-4 video transfer with USB 3.0 host device. Results may vary based on host device, file attributes and other factors]
- Transfer to drive up to 15 times faster than standard USB 2.0 drives(1)
- Sleek, durable metal casing
- Easy-to-use password protection for your private files(3) [(3)Password protection uses 128-bit AES encryption and is supported by Windows 7, Windows 8, Windows 10, and Mac OS X v10.9 plus; Software download required for Mac, visit the SanDisk SecureAccess support page]
An extraction API that returns only one image should publish a clear selection policy. For example, it might prefer a candidate whose declared size fits the caller’s requested output, then consider supported media and formats. If callers need to make that decision themselves, returning all candidates with their original metadata is more useful than silently discarding alternatives. That is an API design choice, not a universal browser rule.
| Candidate or signal | What it tells an extractor |
|---|---|
rel="icon" |
A standard icon declaration; inspect the other attributes and retrieve the linked resource. |
rel="shortcut icon" |
A historical declaration Google still documents; include it in discovery for compatibility. |
sizes |
Declared dimensions that can help distinguish candidates; the attribute may be absent or may not settle whether the actual file is suitable. |
type |
Declared media type that can help a consumer select a compatible resource. |
media |
A condition relevant to when a candidate applies; a selector should not assume every candidate is interchangeable. |
apple-touch-icon or apple-touch-icon-precomposed |
An Apple touch icon candidate for an iOS Web Clip or home-screen save, a distinct use from the ordinary browser favicon. |
Ordinary favicon versus Apple touch icon
If the caller wants the icon associated with an iOS Web Clip or home-screen save, treat Apple touch icons as a distinct candidate class rather than assuming the ordinary rel="icon" is the right result. MDN notes that iOS does not use the ordinary rel="icon" link type for this purpose; see MDN’s rel reference.
What to do when there is no icon declaration
When parsing finds no usable declaration, try requesting https://the-site.example/favicon.ico, substituting the site’s origin. This is a conventional fallback: MDN says browsers and applications commonly use that location, and the Website Icon repository’s standard describes it as an HTML Standard fallback.
Rank #3
- What You Get - 2 pack 64GB genuine USB 2.0 flash drives, 12-month warranty and lifetime friendly customer service
- Great for All Ages and Purposes – the thumb drives are suitable for storing digital data for school, business or daily usage. Apply to data storage of music, photos, movies and other files
- Easy to Use - Plug and play USB memory stick, no need to install any software. Support Windows 7 / 8 / 10 / Vista / XP / Unix / 2000 / ME / NT Linux and Mac OS, compatible with USB 2.0 and 1.1 ports
- Convenient Design - 360°metal swivel cap with matt surface and ring designed zip drive can protect USB connector, avoid to leave your fingerprint and easily attach to your key chain to avoid from losing and for easy carrying
- Brand Yourself - Brand the flash drive with your company's name and provide company's overview, policies, etc. to the newly joined employees or your customers
Do not assume the file exists, that it is valid, or that every browser or client follows this path. Treat the fallback like any other candidate: make the request, check its response, and verify that the result is image data you can use. If it fails, report that no retrievable icon was found rather than fabricating a URL or returning the page’s HTML as an image.
Build a basic webpage-to-icon API
A minimal API can accept a webpage URL, fetch its HTML, parse icon links, resolve their URLs, and return either the chosen icon URL or the image itself. The example below is intentionally a discovery endpoint: it returns the declared candidates and uses the root fallback only when it finds none. It does not download, validate, or proxy the resulting image files.
Free tools Windows power users keep installed
One-click scans. No signup required.
Python example with Flask and Beautiful Soup
Install the dependencies with python -m pip install flask requests beautifulsoup4, save the following as app.py, and run it with python app.py. The endpoint is then available locally at http://127.0.0.1:5000/icon?url=https%3A%2F%2Fexample.com.
Rank #4
- GOOD VALUE PACKAGE - 1 Pack 32GB Memory Stick USB 2.0 Flash Drives with great cost performance and high quality.
- BIG CAPACITY - The available capacity: 29.10GB-29.8GB, You can save the data of movies, music, photos, designs, programs, manuals, handouts in a high speed.Good performance in digital data storing, transferring and sharing with families, friends, workmates, clients and machines.
- EASY TO USE & PLUG AND WORK - Support windows 7 / 8 / 10 / Vista / XP / 2000 / ME / NT Linux and Mac OS, Compatible with USB2.0 and below.
- TWISTTURN DESIGN & EASY CARRY - The metal clip rotates 360° round the ABS plastic body which with rubber oil skin feeling finish. The capless design can avoid lossing of cap, and providing efficient protection to the USB port.
- WARRANTY & SUPPORT - SIMMAX logo is laser printed on the USB connector surface, our products are of good quality and we promise that any problem about the product within one year since you buy.
from urllib.parse import urljoin, urlparse
import requests
from bs4 import BeautifulSoup
from flask import Flask, jsonify, request
app = Flask(__name__)
ICON_RELS = {
"icon",
"shortcut icon",
"apple-touch-icon",
"apple-touch-icon-precomposed",
}
@app.get("/icon")
def get_icons():
page_url = request.args.get("url", "")
parsed = urlparse(page_url)
if parsed.scheme not in {"http", "https"} or not parsed.netloc:
return jsonify(error="url must be an absolute HTTP or HTTPS URL"), 400
try:
response = requests.get(
page_url,
timeout=15,
headers={"User-Agent": "FaviconExtractor/1.0"},
)
response.raise_for_status()
except requests.RequestException as exc:
return jsonify(error="page request failed", detail=str(exc)), 502
soup = BeautifulSoup(response.text, "html.parser")
candidates = []
for link in soup.find_all("link", href=True):
rel_values = link.get("rel", [])
rel_text = " ".join(rel_values) if isinstance(rel_values, list) else str(rel_values)
rel_lower = rel_text.lower()
if not any(rel == rel_lower or rel in rel_lower.split() for rel in ICON_RELS):
continue
candidates.append({
"rel": rel_text,
"url": urljoin(response.url, link["href"]),
"type": link.get("type"),
"sizes": link.get("sizes"),
"media": link.get("media"),
})
if not candidates:
origin = f"{urlparse(response.url).scheme}://{urlparse(response.url).netloc}"
candidates = [{
"rel": "fallback",
"url": urljoin(origin, "/favicon.ico"),
"type": None,
"sizes": None,
"media": None,
}]
return jsonify(page_url=response.url, candidates=candidates)
if __name__ == "__main__":
app.run(host="127.0.0.1", port=5000, debug=False)
For production, do not deploy this sample as an unrestricted public fetch endpoint. Its input URL controls an outbound request. Restrict destinations or block private and link-local address ranges, re-check resolved addresses after redirects, cap response size and redirect count, and use a controlled network egress policy. Also consider caching, concurrency limits, and a separate request to validate each icon before presenting it as retrieved. These are operational and security measures for a URL-fetching service; they are not properties supplied automatically by the HTML parser.
Choosing extraction behavior for real callers
Return a URL, image bytes, or both
- Icon URL: Small response and useful when a client can fetch the resource itself. The resource can change or become inaccessible after the API responds.
- Image bytes: Convenient for clients that need a direct result, but your API must make a second request, handle content types and failures, and decide whether to cache or proxy the resource.
- Candidates plus metadata: The most flexible result when callers have their own size, format, or platform requirements. Preserve each candidate’s declaration rather than returning an unexplained winner.
Make “not found” different from “request failed”
A page fetch can fail before icon discovery begins. An icon URL can also be discovered successfully but return an error, a redirect, or non-image content. Represent these states separately in your API response: page retrieval failure, no declared or fallback candidate, candidate found but resource retrieval failure, and successful image retrieval are not equivalent outcomes.
Do not infer Google Search display from successful extraction. Google’s crawler-access and image requirements are guidance for eligibility in Search, not a universal favicon-extraction specification.
Outdated Drivers Are Slowing You Down
One free scan finds every outdated or missing driver and matches the right update for your exact hardware.Free scan · exact hardware matchWindows Errors? Fix Them Before They Spread
Repair common Windows errors and clear accumulated junk for a smoother, more stable PC - no reinstall needed.Free scan · no reinstallBest Value
- 【16GB Flash Drive】USB flash drives with 16GB capacity, meet your needs of daily use on work, school, home and travelling for photos, music, videos, files storage and transfer. IMEASON thumb drives can be used to store different files, easy to data backup.
- 【Metal Swivel Cap Design】USB thumb drive is metal swivel cover provides extra protection for the usb thumbdrive connector, no usb drive cap to lose; keychain design makes it easier to carry without worrying lose it.
- 【Wide Compatibility】USB drive supports Windows 7/8/10/11 / Vista / XP / Unix / 2000 / ME / NT Linux and Mac OS, also Supports USB 2.0 and 1.1 ports. USB Stick support TV, desktop, notebook computer, car, audio and other device. The USB Memory Stick is your great data storage and transfer companion with traveling and working.
- 【Easy to use】usb memory stick is plug and play without any software installation. Just simply plug the Flashdrive into the port of your USB-compatible devices such as computer, laptop to start data storage or transmission.
- 【What You Get】16 GB USB Flash Drive Thumb Drive, The default format of the usb storage flash drive is FAT32.
Favicon extraction is not Google Search display
Google Search Central’s rules address whether a favicon may be eligible to appear next to a result. Google says its crawler must be able to access both the homepage and the icon; the favicon must be square and at least 8 by 8 pixels, and a size larger than 48 by 48 pixels is recommended. Google lists BMP, GIF, ICO, PNG, JPEG, PPM, and TIFF as supported formats and recommends keeping the icon URL stable. These are Google Search guidelines, not requirements for every browser or for a general-purpose extractor.
Even a site that follows the guidance is not guaranteed to show its favicon in Search. Google states: “A favicon isn’t guaranteed to appear in Google Search results, even if all guidelines are met.” See the current Google Search Central favicon guidance.
Troubleshooting common extraction failures
- No icon links found: The page may not declare one in the returned HTML. Try the root
/favicon.icofallback, then report no result if that request also fails. - The returned icon URL is wrong: Resolve the
hrefagainst the final document URL after redirects. Do not concatenate the document URL and attribute as text. - Several icons are returned: This is normal. Inspect
sizes,type, andmedia; either document your selection rule or return the candidates for the caller to choose. - An Apple device needs a different image: Include Apple touch icon relations and keep that candidate class separate from ordinary browser favicons.
- The candidate URL does not produce an image: A declaration only identifies a resource; it does not prove the resource is reachable or valid. Request it and handle unsuccessful responses and non-image content explicitly.
- Google Search does not show the extracted favicon: Successful retrieval is not a guarantee of Search appearance. Check Google’s crawler access, supported format, square dimensions, size guidance, and stable URL recommendations, while recognizing that Google may still not display it.
- Your endpoint hangs or consumes excessive resources: Apply timeouts, response-size and redirect limits, concurrency caps, and outbound destination controls. A caller-provided URL can otherwise cause a server to fetch unintended or costly resources.
Or skip the browser setup
ScreenshotNeo is a website screenshot API and MCP server by Yorker Media; it captures a page as an image or PDF rather than extracting the favicon declared in its HTML. If your task is to capture the visible webpage instead, one GET request is enough. See the ScreenshotNeo website and API documentation.
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://example.com -o shot.webp
Cookie banners are accepted and removed before capture, along with known newsletter popups and chat widgets; each cleanup step can be turned off. Bot checks, blank pages, failed loads, timeouts, and cache hits are not billed, and the response identifies the page verdict and billing status in headers. An MCP server offers take_screenshot, get_page_info, and capture_pdf tools for AI agents. The Free plan includes 1,000 screenshots per month without a card; paid plans start at $5 for 3,000 screenshots.
Sign up free for 1,000 screenshots a month with no card.
FAQ
Can I get a favicon from a domain without knowing a page URL?
Try the site-root /favicon.ico convention if you have only the origin, but it is not guaranteed to exist. If you can request a page, inspecting its declarations gives you a more informed candidate list.
Does a favicon API need a browser engine?
Basic discovery can be done by fetching and parsing HTML; it does not inherently require rendering the page in a browser. A browser may be relevant for tasks that depend on rendered page behavior, but it is not a substitute for carefully resolving and retrieving declared icon resources.

