L
L
leha782016-05-01 13:26:06
Python
leha78, 2016-05-01 13:26:06

How to parse this xml?

<currencies>
<currency>
<title>Американский доллар</title>
<title_alias>usd</title_alias>
<id>2</id>
<rates>
<buy_rate>67.61</buy_rate>
<sell_rate>68.17</sell_rate>
<date_start>2016-05-01 14:24:00</date_start>
</rates>
</currency>
<currency>
<title>Евро</title>
<title_alias>eur</title_alias>
<id>3</id>
<rates>
<buy_rate>76.08</buy_rate>
<sell_rate>77.90</sell_rate>
<date_start>2016-05-01 14:24:00</date_start>
</rates>
</currency>
<currency>
<title>Российский рубль</title>
<title_alias>rub</title_alias>
<id>4</id>
<rates>
<buy_rate>1.030</buy_rate>
<sell_rate>1.047</sell_rate>
<date_start>2016-05-01 14:24:00</date_start>
</rates>
</currency>
<currency>
<title>Казахский тенге</title>
<title_alias>kzt</title_alias>
<id>5</id>
<rates>
<buy_rate>0.2082</buy_rate>
<sell_rate>0.2200</sell_rate>
<date_start>2016-05-01 14:24:00</date_start>
</rates>
</currency>

You need to pull out buy_rate, sell_rate
import requests
from xml.etree import ElementTree as ET

response = requests.get('http://site.com/api/', stream=True)

tree = ET.fromstring(response.content)

for i in tree.findall('currency'):
    value = (i.find('title_alias'))
    print value

How to get to child elements?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Gornostaev, 2016-05-01
@leha78

import requests
from xml.etree import ElementTree as ET

response = requests.get('http://site.com/api/', stream=True)

tree = ET.fromstring(response.content)

for currency in tree.findall('currency'):
    title = currency.find('title_alias').text
    print(title)

    rates = currency.find('rates')
    print('\tBuy: ' + rates.find('buy_rate').text)
    print('\tSell: ' + rates.find('sell_rate').text)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question