【发布时间】:2020-07-16 14:39:25
【问题描述】:
我正在使用 PyTest 来验证 xml api 响应。 从 api 请求获取以下响应(response.content)
b'<?xml version="1.0" encoding="UTF-8"?>
<Result0>
<Result1>
<Result3>
<Id>2</Id>
<ItemId>https://purchanse.com/62/E00036415</ItemId>
<Place>kpi:62_CS415-TEN-1080p25-ABC</Place>
<Marks>12</Marks>
<SubId>9, 8</SubId>
<Description>https://purchanse.com/62/E00036416</Description>
</Result3>
<Result4>
<Id>2</Id>
<ItemId>https://purchanse.com/64/E00036417</ItemId>
<Place>kpi:63_CS415-TEN-1080p25-XYZ</Place>
<Marks>12</Marks>
<SubId>9</SubId>
<Description>https://purchanse.com/64/E00036416</Description>
</Result4>
</Result1>
</Result0>'
在测试函数中我有这个代码
def test_CheckResponseContent():
element = et.fromstring(response.content)
print("element", element) # Getting <Element 'Result0' at 0x04A88C58> as output
links = element.find("Result0/Result1")
print("L:", links) # Returns 'None'
element = et.fromstring(response.content)
for child in element.iter('*'):
print(child.tag)
我想做这样的断言
Marks == 12
Id == 2
ItemId != "https://purchanse.com/62/E00036416"
我怎样才能为此解析 XML?
有人可以帮忙吗
【问题讨论】:
-
使用 XPath 查询,例如
assert element.find('.//Result1/Result3/Marks').text == '12'等。您从Result0开始,所以所有查询都是相对于Result0节点进行的。 -
@stackoverflow.com/users/2650249/hoefling 非常感谢。如果在任何节点中不满足条件,是否有任何方法可以在循环中检查并将断言标记为“失败”。就像,我想在所有子节点中检查 SubId == 9。所以它应该失败,因为在第一个子节点中我们有
9, 8 -
element.findall('.//Result1//SubId')将为您提供位于Result1子树中的所有SubId元素的列表。从那里,你可以在一个循环中断言或做类似assert all(el.text == '9' for el in element.findall('.//Result1//SubId'))
标签: python-3.x xml pytest elementtree