Files
Python_CookBook_repo/6.数据编码与处理/3.解析简单的XML文档.py
2025-09-10 16:12:45 +08:00

18 lines
622 B
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

from urllib.request import urlopen
from xml.etree.ElementTree import parse
if __name__ == "__main__":
u = urlopen('http://planet.python.org/rss20.xml')
# 使用xml.etree.ElementTree的parse方法来解析文档
doc = parse(u)
print(doc)
# 可以使用.iterfind来对解析出来的文档进行迭代找到所有指定名称的节点
for item in doc.iterfind('channel/item'):
# 使用findtext在节点中寻找需要的数据
title = item.findtext('title')
date = item.findtext('pubDate')
link = item.findtext('link')
print(title, date, link, sep="\n")