【问题标题】:List of distinct XML element names using BeautifulSoup使用 BeautifulSoup 的不同 XML 元素名称列表
【发布时间】:2014-10-31 13:43:49
【问题描述】:

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

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

【问题讨论】:

    标签: python xml tags beautifulsoup


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-11-11
      • 2015-10-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多