1

I am sending a request to an API:

import requests as rq

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

Which prints:

<?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>
  .....

Now how can I get the values of the tags for example "currentSpeed"

MendelG
  • 14,885
  • 4
  • 25
  • 52
MohoTa
  • 27
  • 1
  • 1
  • 9
  • You could try [this](https://stackoverflow.com/questions/18308529/python-requests-package-handling-xml-response) – forgetso Dec 17 '20 at 19:48

1 Answers1

2

This can be done using the BeautifulSoup module.

The code is self-explanatory:

  • Search for the tag by its name using the find_all() method.
  • Create a dictionary where the key is the name of the tag found, and the value is the text of the tag.

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")})

Output:

{'currentspeed': '78'}
MendelG
  • 14,885
  • 4
  • 25
  • 52