【问题标题】:How do I specify a namespace for an xml tag with BeautifulSoup4?如何使用 BeautifulSoup4 为 xml 标签指定命名空间?
【发布时间】:2013-08-21 09:07:08
【问题描述】:

我正在像这样使用 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) 中指定命名空间,以便我可以准确地了解我要查找的内容?

【问题讨论】:

    标签: python python-2.7 beautifulsoup


    【解决方案1】:

    解析时不需要指定“xml”(编辑:除非在 cmets 中存在 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'
    

    【讨论】:

    • 不将其指定为 xml 的问题是 html 解析器无法像 xml 解析器那样处理 CDATA 部分。不幸的是,这并不能回答我的问题。
    猜你喜欢
    • 1970-01-01
    • 2014-09-16
    • 2021-05-16
    • 1970-01-01
    • 1970-01-01
    • 2021-08-14
    • 2013-03-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多