可以使用sitemap库生成网站地图文件sitemap.xml
文档
- https://github.com/cxmcc/sitemap-python
- https://pypi.python.org/pypi/sitemap
安装
pip install sitemap
Urlset
from sitemap import Url, Urlset
from datetime import datetimeurlset = 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 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
from datetime import datetimefrom sitemap import Sitemap, Siteindexsiteindex = 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 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>