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 요청을 차단합니다.

import requests
from bs4 import BeautifulSoup
from urllib.parse import urljoin, urlparse

def get_favicon_url(page_url):
    headers = {'User-Agent': 'Mozilla/5.0 (compatible; FaviconFetcher/1.0)'}
    resp = requests.get(page_url, headers=headers, timeout=10)
    resp.raise_for_status()
    soup = BeautifulSoup(resp.text, 'html.parser')
    # ... continue below

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을 기준으로 해석해야 합니다.

3단계: 아이콘 다운로드 및 저장

URL을 확보했다면 binary content를 가져와 파일에 저장합니다. 확장자를 선택하려면 Content-Type header를 확인하세요.

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

이것이 핵심 logic입니다. 두 함수를 하나의 script로 묶어 command line에서 URL을 받도록 만들 수 있습니다.

자주 발생하는 문제

여러 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로 정의합니다.