使用Python生成带有动态URL的SitemapXML文件的示例代码
发布时间:2023-12-11 14:06:59
以下是使用Python生成带有动态URL的SitemapXML文件的示例代码:
import datetime
from xml.etree.ElementTree import Element, SubElement, tostring
from xml.dom.minidom import parseString
def create_sitemap_xml(urls):
# 创建根元素
root = Element("urlset")
root.set("xmlns", "http://www.sitemaps.org/schemas/sitemap/0.9")
for url in urls:
# 创建url元素
url_elem = SubElement(root, "url")
# 创建loc元素,表示URL地址
loc_elem = SubElement(url_elem, "loc")
loc_elem.text = url
# 创建lastmod元素,表示最后修改时间
lastmod_elem = SubElement(url_elem, "lastmod")
lastmod_elem.text = datetime.datetime.now().isoformat()
# 将XML元素转换为字符串
xml_str = parseString(tostring(root)).toprettyxml(indent=" ")
return xml_str
if __name__ == "__main__":
urls = [
"https://example.com/page1",
"https://example.com/page2",
"https://example.com/page3"
]
sitemap_xml = create_sitemap_xml(urls)
print(sitemap_xml)
上述代码定义了一个create_sitemap_xml函数,接受一个URL列表作为参数,并返回生成的Sitemap XML内容的字符串。代码首先创建根元素urlset,设置其命名空间为http://www.sitemaps.org/schemas/sitemap/0.9。然后,对于每个URL,创建对应的url元素,并在其中添加loc元素表示URL地址以及lastmod元素表示最后修改时间。
最后,在main函数中示例了如何调用create_sitemap_xml函数,并打印生成的Sitemap XML内容的字符串。
你可以根据自己的实际需求修改示例代码中的URL列表,生成符合你网站的动态URL的Sitemap XML文件。
