我正在使用 BeautifulSoup 来解析 XML 文档。是否有直接的方法来获取文档中使用的不同元素名称的列表?
例如,如果这是文档:
<?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>
我想得到: 注意,到,从,标题,正文
最佳答案
您可以使用 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 :
Right now, the only supported XML parser is lxml. If you don’t have lxml installed, asking for an XML parser won’t give you one, and asking for “lxml” won’t work either.
而且,为了跟进这个,那为什么不直接使用特殊的 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']
关于python - 使用 BeautifulSoup 的不同 XML 元素名称列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25705612/