'How to parse CGI respones in python

I have a get request to a URL that its response is a CGI response, how can I read its attributes in python? for example the response is like this:

<CGI_Result>
    <result>0</result>
    <isEnable>0</isEnable>
    <isUseWifi>0</isUseWifi>
    <isConnected>0</isConnected>
    <connectedAP></connectedAP>
    <encryptType>3</encryptType>
    <authMode>2</authMode>
    <keyFormat>0</keyFormat>
    <defaultKey>1</defaultKey>
    <key1></key1>
    <key2></key2>
    <key3></key3>
    <key4></key4>
    <key1Len>64</key1Len>
    <key2Len>64</key2Len>
    <key3Len>64</key3Len>
    <key4Len>64</key4Len>
</CGI_Result>

Here is my code:

import requests
import cgi

r = requests.get(
    "THE_URL"
)

print(r.text)

How can I read key1 value?



Solution 1:[1]

As far as the response is in XML format possible solution is the following:

# pip install requests
# pip install panadas

import requests
import cgi
import pandas as pd

r = requests.get("THE_URL")

df = pd.read_xml(r.text, xpath="/CGI_Result")

df

Returns

enter image description here

Each dataframe cell data can be accessed with iloc like:

df.iloc[0]['key1']

Also dataframe can be converted to dict with:

dct = df.to_dict(orient='records')
dct

Returns

[{'result': 0,
  'isEnable': 0,
  'isUseWifi': 0,
  'isConnected': 0,
  'connectedAP': nan,
  'encryptType': 3,
  'authMode': 2,
  'keyFormat': 0,
  'defaultKey': 1,
  'key1': nan,
  'key2': nan,
  'key3': nan,
  'key4': nan,
  'key1Len': 64,
  'key2Len': 64,
  'key3Len': 64,
  'key4Len': 64}]

Each dict key-value can be accessed like:

dct[0]['key1']

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 gremur