我在python中编程,我正在尝试读取Yamaha网络立体声的状态。我得到以下xml响应
<YAMAHA_AV rsp="GET" RC="0">
<System>
<Power_Control>
<Power>On</Power>
</Power_Control>
</System>
</YAMAHA_AV>
到目前为止一切顺利。现在,我正在尝试搜索Power以获取最新状态。它存在于XML中,但是当我使用XML解析器(如Elementtree)时,我无法找到Power Status值。
import requests
from xml.etree import ElementTree as ET
url = "http://192.168.128.199/YamahaRemoteControl/ctrl"
payload = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<YAMAHA_AV cmd=\"GET\">\r\n<System>\r\n <Power_Control>\r\n <Power>GetParam</Power>\r\n </Power_Control>\r\n</System>\r\n</YAMAHA_AV>"
headers = {
'Content-Type': "text/xml",
'Cache-Control': "no-cache",
'Postman-Token': "9ad57fc1-4c78-a921-5967-bef4d2167214"
}
response = requests.request("POST", url, data=payload, headers=headers)
print(response.text)
rawdata=ET.fromstring(response.content)
result= rawdata.find('Power').text
print (result)
result = rawdata.items()
print(result)
我得到一个空值。所以我逐步通过python交互式,当我在根上使用dir()函数而不是子元素时,我可以看到findall和findtext属性。
>>> root=ET.parse('yamahaPowerStatus.xml').getroot()
>>> print root
<Element 'YAMAHA_AV' at 0x6386bb0>
>>> PC=root.getchildren()[0].getchildren()
>>> print PC
[<Element 'Power_Control' at 0x6386cf0>]
>>> check= PC.findtext('Power')
Traceback (most recent call last):
File "<pyshell#40>", line 1, in <module>
check= PC.findtext('Power')
AttributeError: 'list' object has no attribute 'findtext'
DIR(PC) ['添加','类','包含',' delattr ',' delitem ',' delslice ',' doc ',' eq ','格式', ' ge ',' getattribute ',' getitem ',' getslice ',' gt < / strong>','哈希',' iadd ',' imul ',' init ',' iter ',' le ',' len ',' LT ',' mul ',' ne ','新','减少',' reduce_ex ','< strong> repr ','反转',' rmul ',' setattr ',' setitem ',' setslice ',' sizeof ',' str ','子类别','追加' ,'count','extend','index','insert','pop', '删除','反向','排序']
dir(root) [' class ',' delattr ',' delitem ',' dict ',' doc ','格式',' getattribute ',' getitem ','哈希', ' init ',' len ','模块','新','非零< / strong>',' reduce ',' reduce_ex ',' repr ',' setattr ',' setitem ',' sizeof ',' str ','子类别',' weakref ','_ children','append','attrib','clear','copy','extend','find','findall','findtext','get','getchildren','getiterator ','insert','items','iter','iterfind','itertext','keys','makeelement','remove','set','tag','tail','text']
那么我做错了什么? XML响应似乎格式正确。我尝试使用其他XML解析器,但结果相同。我也尝试将其转换为JSON,但结果相同。我查看过youtube视频,我试图找到类似的东西,但没有运气。我想我做的事情从根本上说是错误的。
答案 0 :(得分:0)
我不太明白为什么会这样,所以我愿意接受评论。出于某种原因,我必须使用&#39; for循环&#39;即使我知道只有一个条目。
tree=ET.fromstring(response.content)
for power_name in tree.findall('.//Power_Control/Power'):
result= power_name.text
print result