使用Python从字符串解析XML

2024-09-30 00:33:01 发布

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

我从登录屏幕后面的URL中提取XML。我可以输入我的凭证并获取XML,但是我在解析这个字符串时遇到了问题。我认为这是一个XML标记列表。不管怎样,XML看起来是这样的:

<Report Type="SLA Report" SiteName="Get Dataset Metadata" SLA_Name="Get Dataset Metadata" SLA_Description="Get Dataset Metadata" From="2018-11-27 00:00" Thru="2018-11-27 23:59" obj_device="4500" locations="69,31,"><Objective Type="Availability"><Goal>99.93</Goal><Actual>100.00</Actual><Compliant>Yes</Compliant><Errors>0</Errors><Checks>2878</Checks></Objective><Objective Type="Uptime"><Goal/><Actual/><Compliant/><Errors>0</Errors><Checks>0</Checks></Objective><Objective Type="Response Time"><Goal>300.00</Goal><Actual>1.7482</Actual><Compliant>Yes</Compliant><Errors>0</Errors><Checks>2878</Checks></Objective><MonitoringPeriods><Monitor><Exclude>No</Exclude><DayFrom>Sunday</DayFrom><TimeFrom>00:00</TimeFrom><DayThru>Sunday</DayThru><TimeThru>23:59</TimeThru></Monitor><Monitor><Exclude>No</Exclude><DayFrom>Monday</DayFrom><TimeFrom>00:00</TimeFrom><DayThru>Monday</DayThru><TimeThru>23:59</TimeThru></Monitor>

我想得到标签之间的所有东西和标签之间的所有东西。我想把它加载到一个数据帧中。就这样。我该怎么做?你知道吗

我想我可以用树根,像这样:

REQUEST_URL = 'https://URL'
response = requests.get(REQUEST_URL, auth=(login, password))
xml_data = response.text.encode('utf-8', 'ignore') 
tree = ET.parse(xml_data)
root = tree.getroot()

但这只会给我NameError: name 'tree' is not defined&;NameError: name 'root' is not defined。我希望有一个或两个班轮,把一切整理好。到目前为止,我还没有发现任何有用的东西。你知道吗

print(response.text) gives me:

<?xml version='1.0' standalone='yes'?><Report Type='SLA Report'
 SiteName='Execute Query'
 SLA_Name='Execute Query'
 SLA_Description='Execute Query'
 From='2018-11-27 00:00'
 Thru='2018-11-27 23:59' 
 obj_device='4500'
 locations='69,31,'
>
<Objective Type='Availability'>
<Goal>99.93</Goal>
<Actual>99.93</Actual>
<Compliant>Yes</Compliant>
<Errors>2</Errors>
<Checks>2878</Checks>
</Objective>
<Objective Type='Uptime'>
<Goal></Goal>
<Actual></Actual>
<Compliant></Compliant>
<Errors>0</Errors>
<Checks>0</Checks>
</Objective>
<Objective Type='Response Time'>
<Goal>300.00</Goal>
<Actual>3.1164</Actual>
<Compliant>Yes</Compliant>
<Errors>0</Errors>
<Checks>2878</Checks>
</Objective>
<MonitoringPeriods>
<Monitor>
<Exclude>No</Exclude><DayFrom>Sunday</DayFrom><TimeFrom>00:00</TimeFrom><DayThru>Sunday</DayThru><TimeThru>23:59</TimeThru>
</Monitor>

Tags: urltypeexcludemonitorcheckserrorsobjectiveactual

热门问题