如何使用BeautifulSoup4为xml标记指定命名空间?

时间:2013-08-19 14:12:59

标签: python python-2.7 beautifulsoup

我正在使用像这样的beautifulsoup4:

from bs4 import BeautifulSoup
xml_string = u"""<something><dcterms:valid><![CDATA[

            start=2012-02-24T00:00:00Z
            end=2030-12-30T00:00:00Z
            scheme=W3C-DTF]]>
        </dcterms:valid></something>"""
soup = BeautifulSoup(xml_string, 'xml')
soup.find('dcterms:valid')  # returns None
soup.find('valid')  # returns the dcterms:valid node

有没有办法在soup.find(tagname)中指定命名空间,所以我可以准确地了解我想找到的内容?

1 个答案:

答案 0 :(得分:0)

解析时不需要指定'xml'(编辑:除非注释中有指向的cdata)。

以下是适用于我的代码示例

>>> soup = BeautifulSoup(xml_string)
>>> soup.find('valid')
>>> soup.find('dcterms:valid')
<dcterms:valid start="2012-02-24T00:00:00Z" end="2030-12-30T00:00:00Z" scheme="W3C-DTF"></dcterms:valid>

>>> item = soup.find('dcterms:valid')
>>> item['start']
u'2012-02-24T00:00:00Z'