How can I access namespaced XML elements using BeautifulSoup?(如何使用 BeautifulSoup 访问命名空间的 XML 元素?)
问题描述
我有一个这样的 XML 文档:
I have an XML document which reads like this:
<xml>
<web:Web>
<web:Total>4000</web:Total>
<web:Offset>0</web:Offset>
</web:Web>
</xml>
我的问题是如何使用 Python 中的 BeautifulSoup 之类的库来访问它们?
my question is how do I access them using a library like BeautifulSoup in python?
xmlDom.web["Web"].Total ?不工作?
xmlDom.web["Web"].Total ? does not work?
推荐答案
BeautifulSoup is't 一个 DOM 库本身(它不实现 DOM API).更复杂的是,您在该 xml 片段中使用命名空间.要解析特定的 XML,您可以使用 BeautifulSoup,如下所示:
BeautifulSoup isn't a DOM library per se (it doesn't implement the DOM APIs). To make matters more complicated, you're using namespaces in that xml fragment. To parse that specific piece of XML, you'd use BeautifulSoup as follows:
from BeautifulSoup import BeautifulSoup
xml = """<xml>
<web:Web>
<web:Total>4000</web:Total>
<web:Offset>0</web:Offset>
</web:Web>
</xml>"""
doc = BeautifulSoup( xml )
print doc.find( 'web:total' ).string
print doc.find( 'web:offset' ).string
如果您不使用命名空间,代码可能如下所示:
If you weren't using namespaces, the code could look like this:
from BeautifulSoup import BeautifulSoup
xml = """<xml>
<Web>
<Total>4000</Total>
<Offset>0</Offset>
</Web>
</xml>"""
doc = BeautifulSoup( xml )
print doc.xml.web.total.string
print doc.xml.web.offset.string
这里的关键是 BeautifulSoup 对命名空间一无所知(或关心).因此 web:Web 被视为 web:web 标记,而不是属于 ewebWeb 标记> 命名空间.虽然 BeautifulSoup 将 web:web 添加到 xml 元素字典中,但 python 语法不会将 web:web 识别为单个标识符.
The key here is that BeautifulSoup doesn't know (or care) anything about namespaces. Thus web:Web is treated like a web:web tag instead of as a Web tag belonging to th eweb namespace. While BeautifulSoup adds web:web to the xml element dictionary, python syntax doesn't recognize web:web as a single identifier.
您可以通过阅读文档了解更多信息.
You can learn more about it by reading the documentation.
这篇关于如何使用 BeautifulSoup 访问命名空间的 XML 元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何使用 BeautifulSoup 访问命名空间的 XML 元素?
基础教程推荐
- 与常规 dict 相比,Python manager.dict() 非常慢 2022-01-01
- 用 Python 编写 Fortran 无格式文件 2022-01-01
- 由Python将MP3转换为MIDI(类型错误:无法加载插件:mtg-Melodia:Melodia) 2022-01-01
- Discord.py 缺少必需的参数 2022-01-01
- 将 x 轴刻度更改为自定义字符串 2022-01-01
- 使用生成器和迭代器时 Python 多循环失败 2022-01-01
- pyserial - 可以从线程 a 写入串行端口,是否阻塞从线程 b 读取? 2022-01-01
- 尝试制作WhatsApp机器人 2022-01-01
- numpy float:比算术运算中内置的慢 10 倍? 2022-01-01
- 在 Celery 工作人员中捕获 Heroku SIGTERM 以优雅地关 2022-01-01
