您可以使用find_all() 并为找到的每个标签获取.name:
from bs4 import BeautifulSoup
data = """<?xml version="1.0" encoding="UTF-8"?>
<note>
<to> Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
"""
soup = BeautifulSoup(data, 'xml')
print [tag.name for tag in soup.find_all()]
打印:
['note', 'to', 'from', 'heading', 'body']
请注意,要使其正常工作,您需要安装lxml 模块,因为根据documentation:
目前,唯一支持的 XML 解析器是 lxml。如果你没有
lxml 已安装,要求 XML 解析器不会给你,并且
请求“lxml”也不行。
而且,为了跟进,为什么不直接使用特殊的 XML 解析器呢?
例如,使用lxml:
from lxml import etree
data = """<?xml version="1.0" encoding="UTF-8"?>
<note>
<to> Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
"""
tree = etree.fromstring(data)
print [item.tag for item in tree.xpath('//*')]
打印:
['note', 'to', 'from', 'heading', 'body']
要遵循这一点,为什么要使用第三方来完成如此简单的任务?
例如,使用标准库中的xml.etree.ElementTree:
from xml.etree.ElementTree import fromstring, ElementTree
data = """<?xml version="1.0" encoding="UTF-8"?>
<note>
<to> Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
"""
tree = ElementTree(fromstring(data))
print [item.tag for item in tree.getiterator()]
打印:
['note', 'to', 'from', 'heading', 'body']