python解析sitemap需求

判断是不是sitemapindex,

xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">

如果是sitemapindex则循环解析子xml,如果不是就直接解析xml文件
xml文件需要保留url和lasmod

可以使用Python中的ElementTree库来解析XML。

首先,我们需要将字符串解析为XML元素对象,可以使用ElementTree库中的fromstring()方法实现。

然后通过ElementTree库中的findall()方法,查找sitemap元素,再通过元素的子元素loc和lastmod获取对应的值。

以下是具体代码实现:

import xml.etree.ElementTree as ET

content = '''<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
    <sitemap>
        <loc>https://www.u9seo.com/post-sitemap1.xml</loc>
        <lastmod>2022-10-22T22:04:43+08:00</lastmod>
    </sitemap>
</sitemapindex>'''

# 解析XML
root = ET.fromstring(content)

# 判断是否为sitemapindex类型
if root.tag == '{http://www.sitemaps.org/schemas/sitemap/0.9}sitemapindex':
    # 获取所有子元素sitemap
    sitemaps = root.findall('{http://www.sitemaps.org/schemas/sitemap/0.9}sitemap')
    
    # 遍历获取loc和lastmod值
    for sitemap in sitemaps:
        loc = sitemap.find('{http://www.sitemaps.org/schemas/sitemap/0.9}loc').text
        lastmod = sitemap.find('{http://www.sitemaps.org/schemas/sitemap/0.9}lastmod').text
        
        # 打印测试
        print('loc:', loc)
        print('lastmod:', lastmod)
else:
    print('不是sitemapindex类型')

输出的结果为:

loc: https://www.u9seo.com/post-sitemap1.xml
lastmod: 2022-10-22T22:04:43+08:00

可以看到成功解析初其中的loc和lastmod参数。

该回答引用ChatGPT

根据提供的XML代码,可以判断这是一个sitemapindex文件,因为它的根元素使用了"http://www.sitemaps.org/schemas/sitemap/0.9%22%E5%91%BD%E5%90%8D%E7%A9%BA%E9%97%B4%EF%BC%8C%E5%B9%B6%E4%B8%94%E5%91%BD%E5%90%8D%E4%B8%BA%22sitemapindex%22%E3%80%82

因此,应该按照要求循环解析子XML文件。对于非sitemapindex文件,应该直接解析XML文件,并保留其中的url和lasmod信息。