Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/xml/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
无法在使用Python语言分析XML时访问子节点_Python_Xml_Python 2.7 - Fatal编程技术网

无法在使用Python语言分析XML时访问子节点

无法在使用Python语言分析XML时访问子节点,python,xml,python-2.7,Python,Xml,Python 2.7,我对python脚本语言非常陌生,最近正在研究一个解析器,它解析基于web的xml文件 我能够在python中使用minidom检索除一个元素之外的所有元素,没有任何问题,但是我有一个节点遇到了问题。我从XML文件中需要的最后一个节点是“image”标记中的“url”,这可以在以下XML文件示例中找到: <events> <event id="abcde01"> <title> Name of event </title>

我对python脚本语言非常陌生,最近正在研究一个解析器,它解析基于web的xml文件

我能够在python中使用minidom检索除一个元素之外的所有元素,没有任何问题,但是我有一个节点遇到了问题。我从XML文件中需要的最后一个节点是“image”标记中的“url”,这可以在以下XML文件示例中找到:

<events>
    <event id="abcde01">
        <title> Name of event </title>
        <url> The URL of the Event <- the url tag I do not need </url>
        <image> 
            <url> THE URL I DO NEED </url>
        </image>
    </event>
我收到的错误是:非常感谢你的帮助,凯伦

image_url = im.getElementsByTagName("image")[0].childNodes[0]
IndexError: list index out of range
首先,不要重新编码内容。无需这样做,XML解析器完全能够处理编码内容

接下来,我将使用

from xml.etree import ElementTree as ET

response = urllib.urlopen(base_url)
tree = ET.parse(response)

urls_list = []
for event in tree.findall('.//event[image]'):
    # find the text content of the first <image><url> tag combination:
    image_url = event.find('.//image/url')
    if image_url is not None:
        urls_list.append(image_url.text)
从xml.etree导入ElementTree作为ET
response=urllib.urlopen(基本url)
tree=ET.parse(响应)
URL_list=[]
对于tree.findall('.//event[image]'中的事件):
#查找第一个标记组合的文本内容:
image\u url=event.find('.//image/url')
如果图像url不是无:
url\u list.append(image\u url.text)

这仅考虑具有直接
图像
子元素的
事件
元素。

不要对数据进行解码和重新编码!将解码留给XML解析器。您不能使用代替minidom的任何原因?该URL会为我返回错误响应;我收到一条
身份验证错误
消息。也许你也是?嗨@MartijnPieters,我省略了这个例子中的api键,因为我认为它会使它更简单。我可以插入api键,如果你觉得这将是更有用的,但我没有这个问题,它更是这样访问图像标签的元素。由于在xml数据中发现了一个黑星的编码问题,我不得不在解析xml数据后对其进行解码和重新编码。对于XML输入来说,这看起来根本不是问题!您正在对Unicode数据进行编码,错误不在于XML。最有可能的问题是
print
stament以及您当时的
stdout
中的任何内容。没有回溯是不可能进一步诊断的。不需要API密钥,只需要覆盖所有基础。
from xml.etree import ElementTree as ET

response = urllib.urlopen(base_url)
tree = ET.parse(response)

urls_list = []
for event in tree.findall('.//event[image]'):
    # find the text content of the first <image><url> tag combination:
    image_url = event.find('.//image/url')
    if image_url is not None:
        urls_list.append(image_url.text)