🛠️ToolsShed

사이트맵 XML 생성기

URL, 우선순위, 변경 빈도로 sitemap.xml 파일을 생성합니다.

자주 묻는 질문

코드 구현

from datetime import date
from xml.etree.ElementTree import Element, SubElement, tostring
from xml.dom import minidom

def generate_sitemap(urls: list[dict]) -> str:
    """
    Generate sitemap.xml string.
    Each url dict: { loc, lastmod?, changefreq?, priority? }
    """
    root = Element("urlset")
    root.set("xmlns", "http://www.sitemaps.org/schemas/sitemap/0.9")
    for entry in urls:
        url_el = SubElement(root, "url")
        SubElement(url_el, "loc").text = entry["loc"]
        if "lastmod" in entry:
            SubElement(url_el, "lastmod").text = entry["lastmod"]
        if "changefreq" in entry:
            SubElement(url_el, "changefreq").text = entry["changefreq"]
        if "priority" in entry:
            SubElement(url_el, "priority").text = str(entry["priority"])
    raw = tostring(root, encoding="unicode")
    dom = minidom.parseString(raw)
    return dom.toprettyxml(indent="  ")

urls = [
    {"loc": "https://example.com/",        "lastmod": str(date.today()), "changefreq": "daily",   "priority": 1.0},
    {"loc": "https://example.com/about",   "lastmod": str(date.today()), "changefreq": "monthly", "priority": 0.8},
    {"loc": "https://example.com/contact", "lastmod": str(date.today()), "changefreq": "monthly", "priority": 0.5},
]
print(generate_sitemap(urls))

Comments & Feedback

Comments are powered by Giscus. Sign in with GitHub to leave a comment.