python-3.x - xml.etree.ElementTree >> Python >> 如何访问子元素并进行断言
问题描述
我正在使用 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?
有人可以帮忙吗
解决方案
您有多个带有提及名称的标签,因此应为这些标签的每个父级分别执行相应的检查集。
为此,请尝试以下代码,可能没有打印语句:
for it in element.findall('Result1/*'):
print(it.tag)
mrks = it.findtext('Marks')
id = it.findtext('Id')
itmId = it.findtext('ItemId')
print(mrks, id, itmId)
assert mrks == '12'
assert id == '2'
assert itmId != 'https://purchanse.com/62/E00036416'
推荐阅读
- python - 如何使用 python-requests 在烧瓶中修复“太多的值无法解包”
- javascript - “以 10 为底的二进制数”程序
- angular - 如何将 Tab Header 文本换行成 2 行?
- c# - “AnyCPU”平台目标上的内存分配模式
- kubernetes - Operator Lifecycle Manager (OLM) 与 Helm
- r - 在 R 中运行线性回归时的警告消息
- c++ - 以更健壮和类型安全的方式处理 ASCII 命令
- python - postgis 距离函数和谷歌地图距离计算器结果之间存在显着差异的原因是什么?
- amazon-web-services - 如何使用 Amazon ECS 插件配置 jenkins slave?
- python - 使用平方根方法找到素数