使用BeautifulSoup列出不同的XML元素名称

时间:2014-09-06 23:11:25

标签: python xml tags beautifulsoup

我正在使用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>

我想得到: 注意,来自,标题,身体

1 个答案:

答案 0 :(得分:3)

您可以使用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']
相关问题