用Python比较两个sitemap.xml差异需解析XML提取URL、标准化(小写/去尾斜杠/统协议)、递归处理嵌套sitemapindex,再集合比对新增/缺失URL并格式化输出。

用Python比较两个sitemap.xml的差异,核心是解析XML、提取URL列表,再做集合或有序比对。关键在于处理sitemap可能存在的嵌套(如sitemapindex)、重复URL、规范格式(如末尾斜杠、协议统一),以及输出可读性强的结果。
sitemap.xml本质是XML,推荐用xml.etree.ElementTree(标准库,无需安装)解析。注意:
• 多数sitemap用 <loc></loc> 标签包裹URL;
• 若是sitemapindex(含多个子sitemap),需递归抓取所有<loc></loc>并过滤出以.xml结尾的子链接;
• URL标准化建议:转小写、移除末尾/、统一用https://(若业务要求)。
示例代码片段:
def extract_urls_from_sitemap(file_path):
urls = set()
try:
tree = ET.parse(file_path)
root = tree.getroot()
namespaces = {'ns': 'https://www.php.cn/link/654f3a10edb3bb1755a43cc4f9be9dc6'}import xml.etree.ElementTree as ET
from urllib.parse import urlparse, urlunparse
<p>def normalize_url(url):
parsed = urlparse(url)</p><h1>转小写,去掉末尾/,保留path/query/fragment</h1><pre class='brush:php;toolbar:false;'>path = parsed.path.rstrip('/')
return urlunparse((parsed.scheme, parsed.netloc.lower(), path,
parsed.params, parsed.query, parsed.fragment))先尝试找普通url条目
for loc in root.findall('.//ns:loc', namespaces):
if loc.text:
urls.add(normalize_url(loc.text.strip()))
# 若是sitemapindex,递归处理子sitemap(这里简化为只读本地文件,实际需HTTP请求)
except Exception as e:
print(f"解析失败 {file_path}: {e}")
return urls
拿到两个标准化URL集合后,常用比对方式有:
立即学习“Python免费学习笔记(深入)”;
urls_a - urls_b
urls_b - urls_a
hashlib.md5(url.encode()).hexdigest()),但通常标准化后集合差已足够真实场景中,sitemap常托管在https://example.com/sitemap.xml,且可能包含嵌套引用。此时需:
timeout和headers防被拒)<sitemapindex></sitemapindex>结构,对每个子<loc></loc>递归下载并解析(注意相对路径需拼接base URL)建议按类别分块输出,带行号和简单统计:
# 示例输出结构
=== 新增URL(sitemap_A 比 sitemap_B 多出) ===
1. https://example.com/blog/new-post
2. https://example.com/products/item-77
<p>=== 缺失URL(sitemap_A 中已无,但 sitemap_B 仍有) ===</p><ol><li><a href="https://www.php.cn/link/65951d951d3b5df75fc887290a473774">https://www.php.cn/link/65951d951d3b5df75fc887290a473774</a></li><li><a href="https://www.php.cn/link/df0d020fc9a3e0bafef47e229b498ba5">https://www.php.cn/link/df0d020fc9a3e0bafef47e229b498ba5</a></li></ol><p>总计:新增 2 条,缺失 2 条,共同 142 条
也可导出为CSV或JSON,方便后续导入Excel或CI流程校验。
以上就是如何用Python脚本比较两个sitemap.xml的差异的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号