Python - 如何解析 xml 响应并将元素值存储在变量中?

Python - How to parse xml response and store a elements value in a variable?(Python - 如何解析 xml 响应并将元素值存储在变量中?)
本文介绍了Python - 如何解析 xml 响应并将元素值存储在变量中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我正在从 API 调用中获取 XML 响应.

I am getting the XML response from the API call.

我需要testId";此响应的属性值.请帮我解决这个问题.

I need the "testId" attribute value from this response. Please help me on this.

r = requests.get( myconfig.URL_webpagetest + "?url=" + testurl + "&f=xml&k=" + myconfig.apikey_webpagetest )
xmltxt = r.content
print(xmltxt)
testId = XML(xmltxt).find("testId").text
r = requests.get("http://www.webpagetest.org/testStatus.php?f=xml&test=" + testId )

xml 响应:

<?xml version="1.0" encoding="UTF-8"?>
<response>
    <statusCode>200</statusCode>
    <statusText>Ok</statusText>
    <data>
        <testId>180523_YM_054fd7d84fd4ea7aed237f87289e0c7c</testId>
        <ownerKey>dfc65d98de13c4770e528ef5b65e9629a52595e9</ownerKey>
        <jsonUrl>http://www.webpagetest.org/jsonResult.php?test=180523_YM_054fd7d84fd4ea7aed237f87289e0c7c</jsonUrl>
    </data>
</response>

产生以下错误:

Traceback (most recent call last):
  File "/pagePerformance.py", line 52, in <module>
    testId = XML (xmltxt).find("testId").text
AttributeError: 'NoneType' object has no attribute 'text'

推荐答案

使用以下方法从响应中收集testId:-

Use the following to collect testId from response:-

import xml.etree.ElementTree as ET

response_xml_as_string = "xml response string from API"
responseXml = ET.fromstring(response_xml_as_string)
testId = responseXml.find('data').find('testId')
print testId.text

这篇关于Python - 如何解析 xml 响应并将元素值存储在变量中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

python arbitrarily incrementing an iterator inside a loop(python在循环内任意递增迭代器)
Joining a set of ordered-integer yielding Python iterators(加入一组产生 Python 迭代器的有序整数)
Iterating over dictionary items(), values(), keys() in Python 3(在 Python 3 中迭代字典 items()、values()、keys())
What is the Perl version of a Python iterator?(Python 迭代器的 Perl 版本是什么?)
How to create a generator/iterator with the Python C API?(如何使用 Python C API 创建生成器/迭代器?)
Python generator behaviour(Python 生成器行为)