【问题标题】:Parsing XML using BeautifulSoup or minidom使用 BeautifulSoup 或 minidom 解析 XML
【发布时间】:2015-03-21 19:03:06
【问题描述】:

我有类似这样的 XML

#filename sample.xml
<tag>
<tag1>
<tag2 property="something"/>
<tag2 property="something1"/>
<tag2 property="something2">value</tag2>
<tag2 property="something3">
<tag3>
<tag4 data="data1"/>
<tag4 data="data2"/>
</tag3>
</tag2>
</tag1>
</tag>

我想提取'data1''data2'。我正在尝试这样的事情:

f=open('sample.xml')
fdata=f.read()
xmldata=BeautifulSoup(fadata)
print (xmldata.tag.tag1.tag2.tag3.tag4["data"])

但是它抛出了一个错误:

AttributeError: 'NoneType' object has no attribute 'tag4'

【问题讨论】:

  • BeautifulStoneSoup 属于 过时 BeautifulSoup 3;你应该使用 BeautifulSoup4 / bs4。 BS3 不能正确解析 XML,而 BS4 可以。
  • @AnttiHaapala 使用 bs4。另外如何使用 xml.dom.minidom 来实现?

标签: python xml-parsing beautifulsoup minidom


【解决方案1】:

print 函数由于多个 tag2s 而失败。一种解决方案是使用.findAll('tag2') 检索所有标签。

这是一个工作示例:

#! /usr/bin/python

from bs4 import BeautifulSoup
f=open('sample.xml')
fdata=f.read()
xmldata=BeautifulSoup(fdata)

alltags2 = xmldata.tag.tag1.findAll('tag2')

for tag2 in alltags2:
    alltags3 = tag2.findAll('tag3')
    for tag3 in alltags3:
        alltags4 = tag3.findAll('tag4')
        for tag4 in alltags4:
            print "The data I got was :\"%s\"" % (tag4["data"])

亲切的问候,

【讨论】:

    【解决方案2】:

    一种可能的方法是使用select() 方法将CSS 选择器语句作为参数传递。例如,如果你真的想严格选择具有这样祖先层次结构的&lt;tag4&gt;

    .....
    xmldata=BeautifulSoup(fadata)
    for tag4 in xmldata.select("tag > tag1 > tag2 > tag3 > tag4"):
        print tag4["data"]
    

    上面将打印以下内容:

    data1
    data2
    

    或者,如果您只需要所有 &lt;tag4&gt; 元素,无论它们位于 XML 中的哪个位置,您都可以简单地使用 xmldata.select("tag4")

    【讨论】:

    • 如果我想获取标签 4 的父节点,那么应该怎么做?我试过x=xmldata.select('tag4') for node in x: print (node.parentNode)
    • 你可以试试:node.parent 而不是node.parentNode
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-31
    • 2017-09-22
    • 2018-10-23
    • 1970-01-01
    • 2015-02-18
    相关资源
    最近更新 更多