欢迎访问宙启技术站
智能推送

使用Python生成带有URL优先级的SitemapXML文件的示例代码

发布时间:2023-12-11 14:05:25

以下是一个使用Python生成带有URL优先级的Sitemap XML文件的示例代码:

from xml.etree.ElementTree import Element, SubElement, tostring
from xml.dom import minidom

def create_sitemap(urlset):
    root = Element('urlset')
    for url, priority in urlset.items():
        url_element = SubElement(root, 'url')
        
        loc_element = SubElement(url_element, 'loc')
        loc_element.text = url
        
        priority_element = SubElement(url_element, 'priority')
        priority_element.text = str(priority)

    return root

def prettify(elem):
    rough_string = tostring(elem, encoding='utf-8')
    reparsed = minidom.parseString(rough_string)
    return reparsed.toprettyxml(indent="  ")

# 示例使用
urlset = {
    'https://www.example.com/page1': 0.8,
    'https://www.example.com/page2': 0.6,
    'https://www.example.com/page3': 0.4
}

sitemap = create_sitemap(urlset)
xml_string = prettify(sitemap)

with open('sitemap.xml', 'w') as f:
    f.write(xml_string)

在示例代码中,我们首先定义了两个函数:create_sitemapprettify

create_sitemap函数接受一个字典urlset作为参数,该字典的键是URL,值是对应URL的优先级。函数将创建一个XML文档树,包含每个URL及其优先级元素,并返回根元素。

prettify函数接受一个XML元素elem作为参数,并使用minidom模块将其转换为带有缩进的漂亮格式的字符串。

在示例使用部分,我们定义了一个示例的urlset字典,键是URL,值是对应URL的优先级。然后,我们调用create_sitemap函数生成XML树,并使用prettify函数将其转换为漂亮格式的字符串。

最后,我们将字符串写入名为sitemap.xml的文件中。

使用该示例代码,你可以根据自己的需求更改或扩展sitemap字典,以生成包含任意数量URL和优先级的Sitemap XML文件。