想整理一个网站的内容,Sitemap 可以作为起点。它能提供 URL,有时还有 lastmod 等字段,但不保证包含网站所有页面,更不能单凭这些字段判断实际流量和发布频率。

Sitemap 数据能说明什么?,正文内容要点图

先确认文件类型与来源

普通站点地图使用 urlset,站点地图索引使用 sitemapindex。下面示例只读取自己导出或有权使用的小型本地 urlset 文件,不联网,不自动递归其他地址。索引文件应先确认其子文件范围,再分别处理。

提取 URL 与 lastmod

from pathlib import Path
import csv
import xml.etree.ElementTree as ET
from urllib.parse import urlsplit

raw = Path("sitemap.xml").read_bytes()
if len(raw) > 5_000_000:
    raise ValueError("Use a smaller local file")
text = raw.decode("utf-8-sig")
if "<!DOCTYPE" in text.upper() or "<!ENTITY" in text.upper():
    raise ValueError("DTD and entity declarations are not accepted")
root = ET.fromstring(text)
ns = {"s": "http://www.sitemaps.org/schemas/sitemap/0.9"}
if root.tag != "{http://www.sitemaps.org/schemas/sitemap/0.9}urlset":
    raise ValueError("Expected a namespaced urlset")
rows, seen = [], set()
for item in root.findall("s:url", ns):
    url = (item.findtext("s:loc", default="", namespaces=ns)).strip()
    try:
        u = urlsplit(url)
    except ValueError:
        continue
    if u.scheme not in ("http", "https") or not u.netloc or url in seen:
        continue
    seen.add(url)
    lastmod = item.findtext("s:lastmod", default="", namespaces=ns).strip()
    rows.append([url, lastmod])
with open("sitemap_urls.csv", "x", encoding="utf-8-sig", newline="") as f:
    writer = csv.writer(f)
    writer.writerow(["url", "lastmod_raw"])
    for row in rows:
        writer.writerow(["'" + v if v.lstrip().startswith(("=", "+", "-", "@")) else v for v in row])

分析时保留字段含义

lastmod 应表示页面的重要修改时间,不等于首次发布日。缺失、无效或统一刷新的日期,应标记为未知,不能据此绘制“每天发文量”。目录也不一定等于栏目,需要与网站真实结构对应。

与内容和搜索数据一起使用

可以按目录整理页面,再结合标题、CMS 分类和已授权搜索数据分析。URL 清单本身不能说明质量,也不能把未出现的地址直接列为删除对象。

参考Sitemap 的作用理解数据范围。脚本帮助整理素材,最终的内容判断仍应依据页面事实与业务需求。

0.021944s