如何在sitemap.xml中创建?



我不能用以下代码创建站点地图?

from usp.tree import sitemap_tree_for_homepage
tree = sitemap_tree_for_homepage('')
print(tree)
for page in tree.all_pages():
print(page)

站点地图布局如下:

<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<url>
<loc>http://www.example.com/</loc>
<lastmod>2005-01-01</lastmod>
<changefreq>monthly</changefreq>
<priority>0.8</priority>
</url>
</urlset> 

在这个线程中你可以读到如何创建一个xml文件:

from usp.tree import sitemap_tree_for_homepage
import xml.etree.cElementTree as ET
import simplejson as json
tree = sitemap_tree_for_homepage('https://www.nytimes.com/')
root = ET.Element("urlset", xmlns="http://www.sitemaps.org/schemas/sitemap/0.9")
for page in tree.all_pages():
url = page.url
prio = json.dumps(page.priority, use_decimal=True)
# format YYYY-MM-DDThh:mmTZD see: https://www.w3.org/TR/NOTE-datetime
lm = page.last_modified.strftime("%Y-%m-%dT%H:%M%z")
cf = page.change_frequency.value
urlel = ET.SubElement(root, "url")
ET.SubElement(urlel, "loc").text = url
ET.SubElement(urlel, "lastmod").text = lm
ET.SubElement(urlel, "changefreq").text = cf
ET.SubElement(urlel, "priority").text = prio
ET.indent(root, "  ") # pretty print
xmltree = ET.ElementTree(root)
xmltree.write("sitemap.xml", encoding="utf-8", xml_declaration=True )

如果您希望lastmod是今天的日期。从datetime导入日期。

from datetime import date

和替换

page.last_modified.strftime("%Y-%m-%dT%H:%M%z")

date.today().strftime("%Y-%m-%dT%H:%M%z")

sitemap.xml

<?xml version='1.0' encoding='utf-8'?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<url>
<loc>https://www.example.com/</loc>
<lastmod>2022-07-19T15:24+0000</lastmod>
<changefreq>daily</changefreq>
<priority>0.8</priority>
</url>
<url>
<loc>https://www.example.com/about</loc>
<lastmod>2022-07-19T15:24+0000</lastmod>
<changefreq>daily</changefreq>
<priority>0.8</priority>
</url>
</urlset>

如果您使用https://www.example.com/作为您的url,您将不会得到上面的输出。因为example.com没有sitemap.xml。所以请使用另一个url。

最新更新