Python – How to parse xml response and store a elements value in a variable?

I am getting the XML response from the API call.

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
testId = XML(xmltxt).find("testId").text
r = requests.get("" + testId )

xml response:

enter image description here

<?xml version="1.0" encoding="UTF-8"?>

The following error is produced:

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


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

Leave a Reply

Your email address will not be published. Required fields are marked *