Python写sitemap.xml生成器源码,SEO应用实战
一、Python在SEO中的核心应用
Python在SEO领域的典型应用场景包括:批量生成sitemap.xml、自动提交搜索引擎、抓取与监控页面收录状态、批量生成规范化的meta标签和结构化数据、爬取并分析竞争对手内容。其中,用Python自动生成sitemap.xml文件是门槛最低、见效最快的实践——它替代了手动编辑XML的繁琐操作,确保网站每次更新后都能快速产出符合Sitemaps协议的索引文件。
二、sitemap.xml生成器完整源码
以下代码可直接保存为 make_sitemap.py 运行,支持扫描目录、生成带分页的sitemap.xml,并自动写入 lastmod、changefreq、priority 字段。
import os
import time
from pathlib import Path
from datetime import datetime
BASE_URL = "https://www.yourdomain.com"
STATIC_DIR = Path("./static_pages") # 存放HTML文件的目录
OUTPUT_DIR = Path("./sitemap") # 输出目录
CHANGEFREQ = "weekly"
PRIORITY = "0.7"
MAX_URLS_PER_FILE = 50000 # Sitemaps协议上限
def collect_urls():
"""遍历目录,收集所有HTML页面URL"""
urls = []
now = datetime.now().strftime("%Y-%m-%d")
for f in sorted(STATIC_DIR.rglob("*.html")):
rel = f.relative_to(STATIC_DIR).as_posix()
urls.append({
"loc": f"{BASE_URL}/{rel}",
"lastmod": now,
"changefreq": CHANGEFREQ,
"priority": PRIORITY
})
return urls
def write_sitemap(urls, path):
"""将URL列表写入单个sitemap.xml文件"""
xml = ['<?xml version="1.0" encoding="UTF-8"?>']
xml.append('<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">')
for u in urls:
xml.append(" <url>")
xml.append(f' <loc>{u["loc"]}</loc>')
xml.append(f' <lastmod>{u["lastmod"]}</lastmod>')
xml.append(f' <changefreq>{u["changefreq"]}</changefreq>')
xml.append(f' <priority>{u["priority"]}</priority>')
xml.append(" </url>")
xml.append("</urlset>")
path.write_text("n".join(xml), encoding="utf-8")
def main():
OUTPUT_DIR.mkdir(exist_ok=True)
all_urls = collect_urls()
total = len(all_urls)
print(f"共收集 {total} 个URL")
# 分页写入
for i in range(0, total, MAX_URLS_PER_FILE):
chunk = all_urls[i:i + MAX_URLS_PER_FILE]
idx = i // MAX_URLS_PER_FILE + 1
out = OUTPUT_DIR / f"sitemap-{idx}.xml"
write_sitemap(chunk, out)
print(f"已生成 {out}({len(chunk)} 条)")
# 生成sitemap索引文件(当存在多个分片时)
if total > MAX_URLS_PER_FILE:
idx_urls = []
for i in range(0, total, MAX_URLS_PER_FILE):
n = i // MAX_URLS_PER_FILE + 1
idx_urls.append(f"{BASE_URL}/sitemap/sitemap-{n}.xml")
xml = ['<?xml version="1.0" encoding="UTF-8"?>']
xml.append('<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">')
for u in idx_urls:
xml.append(f' <sitemap><loc>{u}</loc></sitemap>')
xml.append("</sitemapindex>")
(OUTPUT_DIR / "sitemap-index.xml").write_text("n".join(xml), encoding="utf-8")
print("全部完成。")
if __name__ == "__main__":
main()
三、使用方法
1. 准备目录:将全部静态HTML页面放入 static_pages/,按真实URL路径存放子目录。
2. 修改配置:编辑脚本顶部的 BASE_URL、STATIC_DIR、OUTPUT_DIR 为实际值。
3. 运行:执行 python make_sitemap.py,输出目录即生成一个或多个 sitemap-N.xml。
4. 部署:将生成的XML文件上传至网站根目录的 /sitemap/ 路径下。
5. 提交搜索引擎:在 Google Search Console 或百度搜索资源平台的”sitemap”入口提交 https://www.yourdomain.com/sitemap/sitemap-index.xml(单文件则直接提交对应XML)。
四、关键注意事项
| 要点 | 说明 |
|---|---|
| URL上限 | 单个sitemap文件最多5万条URL,代码已自动分页 |
| lastmod | 若页面有实际修改时间,建议读取文件mtime替代硬编码日期 |
| 动态站点 | 将 collect_urls 改为遍历数据库或CMS接口获取URL列表即可复用 |
| 编码 | 文件必须以UTF-8编码保存,XML声明中需注明 |
| 定时任务 | 可配合cron/计划任务每日凌晨执行,保持sitemap时效性 |
五、延伸:Python做SEO的其他实用脚本方向
批量改写meta description:读取目录中所有HTML,用正则替换<meta name="description">内容。
死链检测:用requests+BeautifulSoup递归抓取内链,报告404/5xx。
自动提交Ping:生成sitemap后,通过HTTP请求向百度http://www.baidu.com/ping或Google Indexing API推送新URL。
以上脚本均可在同一Python工程内组合调用,形成一套轻量的SEO自动化流水线。
常见问题
《Python写sitemap.xml生成器源码,SEO应用实战》主要讲什么?
Python在SEO领域的典型应用场景包括:批量生成sitemap.xml、自动提交搜索引擎、抓取与监控页面收录状态、批量生成规范化的meta标签和结构化数据、爬取并分析竞争对手内容。
文章提到了哪些重点?
以下代码可直接保存为 make_sitemap.py 运行,支持扫描目录、生成带分页的sitemap.xml,;批量改写meta description:读取目录中所有HTML,用正则替换内容
文章给出了哪些建议?
死链检测:用requests+BeautifulSoup递归抓取内链,报告404/5xx。
一、Python在SEO中的核心应用怎么样?
Python在SEO领域的典型应用场景包括:批量生成sitemap.xml、自动提交搜索引擎、抓取与监控页面收录状态、批量生成规范化的meta标签和结构化数据、爬取并分析竞争对手内容。