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>
相关推荐
wuqingshun3141591 天前
红黑树有哪些特征
java·开发语言·jvm
ValhallaCoder1 天前
hot100-贪心
数据结构·python·算法·贪心算法
忘忧记1 天前
pythonQT图书管理系统的进阶版本
python
sww_10261 天前
SAA ReactAgent工作原理
开发语言·前端·javascript
wuqingshun3141591 天前
说一下什么是fail-fast
java·开发语言·jvm
wuqingshun3141591 天前
知道java NIO吗?和java IO有什么区别?
java·开发语言·jvm
AC赳赳老秦1 天前
2026多模态技术趋势预测:DeepSeek处理图文音视频多格式数据实战指南
java·人工智能·python·安全·架构·prometheus·deepseek
Zik----1 天前
Leetcode22 —— 括号生成
java·开发语言
芒克芒克1 天前
深入浅出Java线程池(三)
java·开发语言
A懿轩A1 天前
【Java 基础编程】Java 常用类速查:包装类、String/StringBuilder、Math、日期类一篇搞定
java·开发语言·python·java常用类