python - 使用 BeautifulSoup 的不同 XML 元素名称列表

标签 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>

我想得到: 注意,到,从,标题,正文

最佳答案

您可以使用 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/

相关文章:

python - 在 Python 3 中绘制 3D 多边形

使用 __file__ 时出现 Python 错误 [WinError 123](文件名、目录名或卷标语法不正确)

java - 运行 Git 命令并从 java 程序解析日志历史记录

php - 使用php脚本将包含word文档的.xml文件插入mysql

html - 你能在 HTML5 中定义自己的自闭合标签吗?

python - feedparser 出现 UndeclaredNamespace 错误

java - 如何在 Spring XML 文件中使用 DOCTYPE

ios - 已经创建的带有标签的 UIViews 变为 NULL

c++ - tinyxml和c++保存数据

Python - 元组和内存管理