可以使用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>