Python如何使用Python确定是否存在特定的XML节点?

2024-10-01 07:44:49 发布

您现在位置:Python中文网/ 问答频道 /正文

以下是我的一些XML代码示例:

<VAST version="2.0">
<Ad id="602678">
<InLine>
<AdSystem>Acudeo Compatible</AdSystem>
<AdTitle>NonLinear Test Campaign 1</AdTitle>
<Description>NonLinear Test Campaign 1</Description>
<Creatives>
<Creative AdID="602678-NonLinear">
</Creative>
</Creatives>
</InLine>
</Ad>
</VAST>

这个XML是在网上提供的,所以我点击一个特定的URL来获取这些数据。但是,在某些情况下,不会返回任何内容,因此我正在寻找一种方法来验证“Creatives”节点是否存在于任何给定时间返回的内容中。我尝试过BeautifulSoup,但运气不好,但我认为它更适合于HTML而不是XML。非常感谢您的帮助,谢谢。你知道吗


Tags: 代码test示例内容inlinedescriptionxmlad
2条回答

假设您从如下URL检索XML:

import requests

r = requests.get(url)
if r.status_code == 200:
    xml_tag_exists(r)

然后您只需构建一个简单的函数,它将根据所需的XML标记是否存在返回True/False

def xml_tag_exists(r):
    return '<Creatives>' in r.text

例如,让我们以following URL为例:

>>> import requests
>>> url = 'http://www.w3schools.com/xml/plant_catalog.xml'
>>> r = requests.get(url)
>>> if r.status_code == 200:
...     print(r.text)

以上内容将返回以下形式的XML:

<CATALOG>
  <PLANT>
    <COMMON>Bloodroot</COMMON>
    <BOTANICAL>Sanguinaria canadensis</BOTANICAL>
    <ZONE>4</ZONE>
    <LIGHT>Mostly Shady</LIGHT>
    <PRICE>$2.44</PRICE>
    <AVAILABILITY>031599</AVAILABILITY>
  </PLANT>
  <PLANT>
    <COMMON>Columbine</COMMON>
    <BOTANICAL>Aquilegia canadensis</BOTANICAL>
    <ZONE>3</ZONE>
    <LIGHT>Mostly Shady</LIGHT>
    <PRICE>$9.37</PRICE>
    <AVAILABILITY>030699</AVAILABILITY>
  </PLANT>
  ...
</CATALOG>

如果我们检查一下标签:

>>> if '<CATALOG>' in r.text:
...     print(True)
...
True

所以,如果我要这么做,我会这样写:

import requests


def xml_tag_exists(r):
    return '<Creatives>' in r.text


def main():
    r = requests.get('your_url_goes_here')
    if r.status_code == 200:
        xml_tag_exists(r)

if __name__ == '__main__':
    main()

也可以使用XPath

from lxml import etree

f = StringIO(YOURS_XML)
tree = etree.parse(f)

creatives_node = tree.xpath('/Creatives')

相关问题 更多 >