【问题标题】:Convert XML to python dictionary将 XML 转换为 python 字典
【发布时间】:2021-03-28 12:51:02
【问题描述】:

我正在向 API 发送请求:

import requests as rq

resp_tf = rq.get("https://api.t....")
tf_text = resp_tf.text

哪些打印:

<?xml version="1.0" encoding="UTF-8"?>
<flowSegmentData version="traffic-service 4.0.011">
<frc>FRC0</frc>
<currentSpeed>78</currentSpeed>
<freeFlowSpeed>78</freeFlowSpeed>
<currentTravelTime>19</currentTravelTime>
<freeFlowTravelTime>19</freeFlowTravelTime>
<confidence>0.980000</confidence>
 <roadClosure>false</roadClosure>
<coordinates>
<coordinate>
  .....

现在如何获取标签的值,例如“currentSpeed”

【问题讨论】:

  • 你可以试试this

标签: python xml api


【解决方案1】:

这可以使用BeautifulSoup 模块来完成。

代码不言自明:

  • 使用find_all() 方法按名称搜索标签。
  • 创建一个字典,其中key 是找到的标签的名称,value 是标签的文本。

from bs4 import BeautifulSoup

xml = """<?xml version="1.0" encoding="UTF-8"?>
<flowSegmentData version="traffic-service 4.0.011">
<frc>FRC0</frc>
<currentSpeed>78</currentSpeed>
<freeFlowSpeed>78</freeFlowSpeed>
<currentTravelTime>19</currentTravelTime>
<freeFlowTravelTime>19</freeFlowTravelTime>
<confidence>0.980000</confidence>
 <roadClosure>false</roadClosure>
<coordinates>
<coordinate>"""

soup = BeautifulSoup(xml, "html.parser")

print({tag.name: tag.text for tag in soup.find_all("currentspeed")})

输出:

{'currentspeed': '78'}

【讨论】:

  • 当然,是的,谢谢。 BS是最简单的方法!
猜你喜欢
  • 2016-08-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-19
  • 2016-10-16
  • 1970-01-01
  • 2012-12-06
  • 2010-12-15
相关资源
最近更新 更多