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>
相关推荐
hhb_6184 小时前
Groovy语法进阶与工程实践指南
开发语言·python
hmywillstronger4 小时前
Rhino 中文字方向问题的解析与解决方案
python
沐知全栈开发4 小时前
R CSV 文件处理指南
开发语言
AI技术增长5 小时前
Pytorch图像去噪实战(四):Attention UNet图像去噪实战,让模型重点恢复边缘和纹理区域
人工智能·pytorch·python
2401_833033625 小时前
如何修复固定定位头部容器中悬浮下拉菜单的错位问题
jvm·数据库·python
秋95 小时前
OceanBase与GreatSQL在Java应用中的性能调优方法有哪些?
java·开发语言·oceanbase
z4424753265 小时前
CSS Grid布局如何实现网格项目的自动增长_设置grid-auto-flow- row
jvm·数据库·python
GeLx5 小时前
从反爬角度:Playwright CDP 模式、Playwright 传统模式与 DrissionPage 的比较
python·程序人生·playwright·drissionpage·pyppeteer·浏览器自动化控制
澈2075 小时前
C++多态编程:从原理到实战
开发语言·c++
m0_740352425 小时前
如何在 SvelteKit 中为动态加载的图片实现响应式悬停覆盖层
jvm·数据库·python