You need to grab a website's favicon in a Python script — maybe for a link preview, a bookmark manager, or a monitoring dashboard. The good news: you don't need a heavy browser automation tool. A few lines with requests and BeautifulSoup will do the job.
This tutorial shows you exactly how to write a python get favicon from url function that handles the common cases. We'll cover parsing the HTML, falling back to /favicon.ico, and saving the binary file.
Prerequisites
You'll need Python 3.7+ and two libraries: requests and beautifulsoup4. Install them with pip:
pip install requests beautifulsoup4
If you prefer not to parse HTML manually, you can also use a library like favicon (available on PyPI), but we'll build it from scratch for full control.
Step 1: Fetch the page HTML
Start by downloading the page source. Use a realistic User-Agent header — some servers block default Python requests.
Always set a timeout. Without it, a slow server can hang your script indefinitely.
Step 2: Look for link rel="icon" tags
The HTML spec defines rel="icon" as the standard way to declare a favicon. Browsers also accept shortcut icon and apple-touch-icon. We'll check all of them, preferring SVG and PNG over ICO.
icon_link = soup.find('link', rel=lambda x: x and 'icon' in x.lower())
if icon_link and icon_link.get('href'):
return urljoin(page_url, icon_link['href'])
# Fallback to /favicon.ico
parsed = urlparse(page_url)
return f'{parsed.scheme}://{parsed.netloc}/favicon.ico'
Note the use of urljoin — favicon hrefs are often relative (e.g., /assets/favicon.png), and you need to resolve them against the page URL.
Step 3: Download and save the icon
Once you have the URL, fetch the binary content and write it to a file. Check the Content-Type header to pick an extension.
def download_favicon(favicon_url, output_path='favicon.ico'):
headers = {'User-Agent': 'Mozilla/5.0 (compatible; FaviconFetcher/1.0)'}
resp = requests.get(favicon_url, headers=headers, timeout=10)
resp.raise_for_status()
content_type = resp.headers.get('Content-Type', '')
if 'png' in content_type:
output_path = output_path.replace('.ico', '.png')
elif 'svg' in content_type:
output_path = output_path.replace('.ico', '.svg')
with open(output_path, 'wb') as f:
f.write(resp.content)
return output_path
That's the core logic. You can wrap both functions into a single script that takes a URL from the command line.
Common pitfalls
Relative URLs: Always resolve with urljoin. A bare href="favicon.ico" will fail if you don't.
Redirects: requests follows redirects by default, but the final URL may differ. Use resp.url as the base for urljoin if you need accuracy.
Missing favicon: Many sites don't have a /favicon.ico. Your fallback will return a 404 — handle it gracefully with a try/except.
Content-Type mismatch: Some servers serve ICO files as image/x-icon or image/vnd.microsoft.icon. Don't rely solely on the extension.
Large files: Favicons are usually small, but set a max size limit (e.g., 1 MB) to avoid downloading huge files by mistake.
If you need to extract multiple icon formats (Apple Touch, manifest icons), consider using a dedicated tool like Mzu favicondl to inspect all available icons. For a deeper dive into favicon formats, see our favicon format guide.
Conclusion
You now have a working Python function to get a favicon from any URL. The key steps are: fetch the page, parse the <link> tags, resolve relative URLs, and download the binary. Handle errors and edge cases, and you're set.
Remember to respect robots.txt and rate limits when scraping many sites. For a complete favicon solution, check out our PHP tutorial for comparison.
Check the documented requirements
The HTML Standard defines rel='icon' as the link relationship for an icon representing the current page.
icon_link = soup.find('link', rel=lambda x: x and 'icon' in x.lower())
if icon_link and icon_link.get('href'):
return urljoin(page_url, icon_link['href'])
# Fallback to /favicon.ico
parsed = urlparse(page_url)
return f'{parsed.scheme}://{parsed.netloc}/favicon.ico'
icon_link = soup.find('link', rel=lambda x: x and 'icon' in x.lower())
if icon_link and icon_link.get('href'):
return urljoin(page_url, icon_link['href'])
# Fallback to /favicon.ico
parsed = urlparse(page_url)
return f'{parsed.scheme}://{parsed.netloc}/favicon.ico'
HTML Standardは、rel='icon'を、現在のページを表すアイコンのリンク関係として定義しています。
Python 스크립트에서 웹사이트의 favicon을 가져와야 한다면 — 링크 미리보기, 북마크 관리 도구, 모니터링 대시보드 같은用途에 필요할 수 있습니다. 좋은 소식은 무거운 browser automation tool이 필요 없다는 것입니다. requests와 BeautifulSoup를 이용한 몇 줄의 코드로 충분합니다.
이 튜토리얼에서는 일반적인 경우를 처리하는 python get favicon from url 함수를 작성하는 방법을 정확히 보여줍니다. HTML 파싱, /favicon.ico로의 fallback, binary file 저장까지 다룹니다.
사전 준비
Python 3.7+와 두 개의 라이브러리가 필요합니다: requests와 beautifulsoup4. pip로 설치합니다.
pip install requests beautifulsoup4
HTML을 직접 파싱하고 싶지 않다면 favicon 라이브러리(PyPI에서 제공) 같은 라이브러리를 사용할 수도 있지만, 전체적인 제어권을 위해 처음부터 직접 구현하겠습니다.
1단계: 페이지 HTML 가져오기
먼저 페이지 소스를 다운로드합니다. 현실적인 User-Agent 헤더를 사용하세요. 일부 서버는 기본 Python 요청을 차단합니다.
timeout은 항상 설정해야 합니다. 설정하지 않으면 느린 서버 때문에 스크립트가 무한정 멈출 수 있습니다.
2단계: link rel="icon" 태그 찾기
HTML 명세는 rel="icon"을 favicon을 선언하는 표준 방법으로 정의합니다. 브라우저는 shortcut icon과 apple-touch-icon도 허용합니다. 이들을 모두 확인하되 ICO보다 SVG와 PNG를 우선합니다.
icon_link = soup.find('link', rel=lambda x: x and 'icon' in x.lower())
if icon_link and icon_link.get('href'):
return urljoin(page_url, icon_link['href'])
# Fallback to /favicon.ico
parsed = urlparse(page_url)
return f'{parsed.scheme}://{parsed.netloc}/favicon.ico'
urljoin을 사용한다는 점에 유의하세요. favicon href는 상대 경로인 경우가 많으며(예: /assets/favicon.png), 이를 페이지 URL을 기준으로 해석해야 합니다.
Content-Type 불일치: 일부 서버는 ICO 파일을 image/x-icon 또는 image/vnd.microsoft.icon으로 제공합니다. extension에만 의존하지 마세요.
대용량 파일: favicon은 보통 작지만, 실수로 매우 큰 파일을 다운로드하지 않도록 최대 크기 제한(예: 1 MB)을 설정하세요.
여러 icon format(Apple Touch, manifest icons)을 추출해야 한다면, 사용 가능한 모든 icon을 확인하기 위해 Mzu favicondl 같은 전용 tool을 고려해 보세요. favicon format에 대해 더 자세히 알아보려면 favicon format guide를 참고하세요.
결론
이제 어떤 URL에서든 favicon을 가져오는 작동하는 Python 함수를 갖게 되었습니다. 핵심 단계는 페이지 fetch, <link> 태그 parse, 상대 URL resolve, binary 다운로드입니다. error와 edge case를 처리하면 준비가 끝납니다.
많은 사이트를 스크래핑할 때는 robots.txt와 rate limit을 준수해야 합니다. 완전한 favicon 솔루션이 필요하다면 비교를 위해 당사의 PHP 튜토리얼을 확인해 보세요.
문서화된 요구 사항 확인
HTML Standard은 rel='icon'을 현재 페이지를 나타내는 icon의 link relationship로 정의합니다.
Necesitas obtener el favicon de un sitio web en un script de Python — quizá para una vista previa de enlace, un gestor de marcadores o un dashboard de monitorización. La buena noticia: no necesitas una herramienta pesada de automatización de navegador. Con unas pocas líneas usando requests y BeautifulSoup lo tendrás resuelto.
Este tutorial te muestra exactamente cómo escribir una función python get favicon from url que cubra los casos habituales. Veremos cómo parsear el HTML, cómo recurrir a /favicon.ico como fallback y cómo guardar el archivo binario.
Requisitos
Necesitas Python 3.7+ y dos librerías: requests y beautifulsoup4. Instálalas con pip:
pip install requests beautifulsoup4
Si prefieres no parsear HTML a mano, también puedes recurrir a una librería como favicon (disponible en PyPI), pero aquí lo construiremos desde cero para tener control total.
Paso 1: Descargar el HTML de la página
Empieza descargando el código fuente de la página. Usa un header User-Agent realista: algunos servidores bloquean las peticiones de Python por defecto.
Establece siempre un timeout. Sin él, un servidor lento puede dejar tu script colgado indefinidamente.
Paso 2: Buscar las etiquetas link rel="icon"
La especificación de HTML define rel="icon" como la forma estándar de declarar un favicon. Los navegadores también aceptan shortcut icon y apple-touch-icon. Los comprobaremos todos, dando preferencia a SVG y PNG frente a ICO.
icon_link = soup.find('link', rel=lambda x: x and 'icon' in x.lower())
if icon_link and icon_link.get('href'):
return urljoin(page_url, icon_link['href'])
# Fallback to /favicon.ico
parsed = urlparse(page_url)
return f'{parsed.scheme}://{parsed.netloc}/favicon.ico'
Fíjate en el uso de urljoin: los href de los favicons suelen ser relativos (por ejemplo, /assets/favicon.png) y necesitas resolverlos respecto a la URL de la página.
Paso 3: Descargar y guardar el icono
Una vez que tengas la URL, obtén el contenido binario y guárdalo en un archivo. Comprueba la cabecera Content-Type para elegir la extensión adecuada.
def download_favicon(favicon_url, output_path='favicon.ico'):
headers = {'User-Agent': 'Mozilla/5.0 (compatible; FaviconFetcher/1.0)'}
resp = requests.get(favicon_url, headers=headers, timeout=10)
resp.raise_for_status()
content_type = resp.headers.get('Content-Type', '')
if 'png' in content_type:
output_path = output_path.replace('.ico', '.png')
elif 'svg' in content_type:
output_path = output_path.replace('.ico', '.svg')
with open(output_path, 'wb') as f:
f.write(resp.content)
return output_path
Esa es la lógica principal. Puedes envolver ambas funciones en un único script que tome una URL desde la línea de comandos.
Errores habituales
URLs relativas: Resuélvelas siempre con urljoin. Un href="favicon.ico" sin resolver fallará si no lo haces.
Redirecciones: requests sigue las redirecciones por defecto, pero la URL final puede cambiar. Usa resp.url como base para urljoin si necesitas precisión.
Favicon ausente: Muchos sitios no tienen un /favicon.ico. Tu fallback devolverá un 404: gestiónalo de forma elegante con un try/except.
Discrepancia en Content-Type: Algunos servidores sirven archivos ICO como image/x-icon o image/vnd.microsoft.icon. No te bases solo en la extensión.
Archivos grandes: Los favicon suelen ser pequeños, pero conviene establecer un límite máximo (por ejemplo, 1 MB) para evitar descargar archivos enormes por error.
Si necesitas extraer varios formatos de iconos (Apple Touch, iconos del manifest), considera usar una herramienta dedicada como Mzu favicondl para inspeccionar todos los iconos disponibles. Para profundizar en los formatos de favicon, consulta nuestra guía de formatos de favicon.
Conclusión
Ahora ya dispones de una función en Python que funciona para obtener un favicon a partir de cualquier URL. Los pasos clave son: obtener la página, analizar las etiquetas <link>, resolver las URL relativas y descargar el binario. Gestiona los errores y los casos límite, y listo.
Recuerda respetar robots.txt y los límites de solicitudes cuando hagas scraping de muchos sitios. Para una solución completa para obtener favicons, consulta nuestro tutorial de PHP y compara las opciones.
Comprueba los requisitos documentados
El estándar HTML define rel='icon' como la relación de enlace para un icono que representa la página actual.
Need favicons for your project?
Download and convert favicons from any website with Mzu favicondl. Free, fast, and no sign-up required.