最简单可靠的方式是用Python标准库xml.etree.ElementTree手动构造符合Sitemap协议的XML,根节点为urlset,每个url包含必填loc及可选lastmod、changefreq、priority,确保loc为绝对URL、lastmod为ISO 8601格式。
用Python生成 sitemap.xml 最简单可靠的方式是手动构造符合Sitemap协议的XML内容,或借助轻量库(如 xml.etree.ElementTree 或第三方库 django-sitemaps / flask-sitemap)。对大多数静态网站或小型动态站,纯Python + 标准库就足够,无需引入复杂框架。
Python 标准库中的 xml.etree.ElementTree 足以生成合法、可被搜索引擎识别的 sitemap。关键点:根节点为 urlset,每个 url 包含 loc(必填),可选 lastmod、changefreq、priority。
loc 是完整、可访问的绝对 URL(如 https://www./link/e4639aefe47ac53c3df3d8f9846b5161blog/post1/)lastmod 格式必须为 YYYY-MM-DD 或 YYYY-MM-DDThh:mm:ss+00:00(推荐 ISO 8601)ElementTree 会自动处理,但手动拼接字符串时需用 xml.sax.saxutils.escape()
以下脚本生成包含 3 个页面的 sitemap.xml,保存到当前目录:
import xml.etree.ElementTree as ET from datetime import datetime创建根元素
urlset = ET.Element("urlset", xmlns="https://www./link/654f3a10edb3bb1755a43cc4f9be9dc6")
定义页面数据(实际项目中可从数据库、文件列表或 CMS API 获取)
pages = [ {"loc": "https://www./link/e4639aefe47ac53c3df3d8f9846b5161", "lastmod": "2025-05-01", "changefreq": "weekly", "priority": "1.0"}, {"loc": "https://www./link/e4639aefe47ac53c3df3d8f9846b5161about/", "lastmod": "2025-04-22", "changefreq": "monthly", "priority": "0.8"}, {"loc": "https://www./link/e4639aefe47ac53c3df3d8f9846b5161blog/", "lastmod": "2025-05-10", "changefreq": "daily", "priority": "0.9"}, ]
for page in pages: url = ET.SubElement(urlset, "url") ET.SubElement(url, "loc").text = page["loc"] ET.SubElement(url, "lastmod").text = page["lastmod"] ET.SubElement(url, "changefreq").text = page["changefreq"] ET.SubElement(url, "priority").text = page["priority"]
写入文件(缩进需手动处理,或用第三方库如 xmltodict / lxml 美化)
tree = ET.ElementTree(urlset) tree.write("sitemap.xml", encoding="utf-8", xml_declaration=True)
print("✅ sitemap.xml 已生成")
运行后得到结构清晰、合规的 XML 文件,可直接部署到网站根目录。
单个 sitemap 最多支持 5 万条 URL,总大小不超过 50MB(压缩后)。超限时需拆分为多个 sitemap 并生成 sitemap_index.xml:
sitemap-1.xml, sitemap-2.xml)sitemapindex 根节点汇总所有子 sitemap 的 loc 和可选 lastmod
Sitemap: https://www./link/e4639aefe47ac53c3df3d8f9846b5161sitemap_index.xml
不推荐手动生成。应将其嵌入网站构建环节:
build 后自动生成django.contrib.sitemaps)
ions):添加 Python 步骤,每次 push 后更新并提交 sitemap.xml
保持 sitemap 与线上内容实时一致,比“一次性生成”更重要。