使用Python中的xml.etree.ElementTree模块解析XML文件,然后遍历所有的URL节点。
示例代码如下:
import xml.etree.ElementTree as ET
# 解析XML文件
tree = ET.parse('sitemap.xml')
root = tree.getroot()
# 遍历所有的URL节点
for url in root.iter('{http://www.sitemaps.org/schemas/sitemap/0.9}url'):
loc = url.find('{http://www.sitemaps.org/schemas/sitemap/0.9}loc').text
print(loc)
其中,http://www.sitemaps.org/schemas/sitemap/0.9
是XML命名空间。
解析XML文件后,使用root.iter
方法遍历所有的URL节点,然后使用url.find
方法获取loc
节点的文本内容,即网站URL。