我是python的新手,只做了几个脚本。
现在,我需要侦听和处理从udp套接字接收的xml文本。
到目前为止,我已经有了第一部分,但我不知道如何继续。
import socket
import lxml.etree
port = 7059
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind(("", port))
print "waiting on port:", port
while 1:
data, addr = s.recvfrom(1024)
print data我正在接收数据,它打印在屏幕上:
<electricity id='4437190066CD'><timestamp>1532728995</timestamp><signal rssi='-78' lqi='94'/><battery level='10%'/><chan id='0'><curr units='w'>609.00</curr><day units='wh'>34.64</day></chan><chan id='1'><curr units='w'>42.00</curr><day units='wh'>2.38</day></chan><chan id='2'><curr units='w'>538.00</curr><day units='wh'>30.43</day></chan></electricity>但我需要获取或解析粗体的de值:
<chan id='0'><curr units='w'>609.00</curr>
<chan id='1'><curr units='w'>42.00</curr>
<chan id='2'><curr units='w'>538.00</curr>并赋值给类似var的东西及其子对象:
power.ch0 = 609.00
power.ch1 = 42.00
power.ch2 = 538.00
使用该变量,然后我将向我的端口监控系统api发出一个请求,以发送这些值。
我通常使用bash编写脚本,我对此很满意,但我认为这一次还不够丰富,python似乎是我的解决方案
提前感谢您的帮助!!
发布于 2018-07-28 08:55:17
有几种方法可以做到这一点。首先,我不知道您在哪里使用xml.etree模块。快速浏览一下文档:https://docs.python.org/3/library/xml.etree.elementtree.html
同样,您也可以使用BeautifulSoup来实现这一点:https://www.crummy.com/software/BeautifulSoup/bs4/doc/
最后,您也可以使用.replace()和.strip()函数来实现这一点
https://stackoverflow.com/questions/51566274
复制相似问题