Python:使用sitemap库生成网站地图文件sitemap.xml

可以使用sitemap库生成网站地图文件sitemap.xml

文档

安装

复制代码
pip install sitemap

Urlset

python 复制代码
from sitemap import Url, Urlset
from datetime import datetime

urlset = Urlset()

url = Url(
    loc='https://www.example.com/',
    lastmod=datetime.now(),
    changefreq='weekly'
)

urlset.add_url(url)

# urlset.to_string()
urlset.write_xml('sitemap.xml')

生成的文件:sitemap.xml

xml 复制代码
<?xml version='1.0' encoding='utf-8'?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9 
    http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd">
    <url>
        <loc>https://www.example.com/</loc>
        <lastmod>2024-07-23</lastmod>
        <changefreq>weekly</changefreq>
    </url>
</urlset>

Siteindex

python 复制代码
from datetime import datetime

from sitemap import Sitemap, Siteindex

siteindex = Siteindex()

sitemap = Sitemap(
    loc='https://www.example.com/sitemap.xml',
    lastmod=datetime.now()
)

siteindex.add_sitemap(sitemap)

# siteindex.to_string()
siteindex.write_xml('sitemap.xml')
xml 复制代码
<?xml version='1.0' encoding='utf-8'?>
<siteindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" 
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
           xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9 
           http://www.sitemaps.org/schemas/sitemap/0.9/siteindex.xsd">
    <sitemap>
        <loc>https://www.example.com/sitemap.xml</loc>
        <lastmod>2024-07-23</lastmod>
    </sitemap>
</siteindex>
相关推荐
数据智能老司机4 小时前
精通 Python 设计模式——分布式系统模式
python·设计模式·架构
数据智能老司机5 小时前
精通 Python 设计模式——并发与异步模式
python·设计模式·编程语言
数据智能老司机5 小时前
精通 Python 设计模式——测试模式
python·设计模式·架构
数据智能老司机5 小时前
精通 Python 设计模式——性能模式
python·设计模式·架构
c8i5 小时前
drf初步梳理
python·django
每日AI新事件5 小时前
python的异步函数
python
这里有鱼汤6 小时前
miniQMT下载历史行情数据太慢怎么办?一招提速10倍!
前端·python
databook15 小时前
Manim实现脉冲闪烁特效
后端·python·动效
程序设计实验室16 小时前
2025年了,在 Django 之外,Python Web 框架还能怎么选?
python
倔强青铜三17 小时前
苦练Python第46天:文件写入与上下文管理器
人工智能·python·面试