0

I want to get the value temperature which is in the <element type = 'air_temperature_maximum'> under <forecast-period>. I only want it for the area 'Melbourne'.

xml source = http://www.bom.gov.au/fwo/IDV10753.xml

I tried the following, but this only prints out the entire parsed xml rather than what i intend to get.

import xml.etree.ElementTree as ET
import requests

url = "http://www.bom.gov.au/fwo/IDV10753.xml"
response = requests.get(url, verify=False).content.decode('UTF-8')

tree = ET.parse(response)
print(tree.find('product').find('amoc').find('forecast').find('area')
.find('forecast-period').find('element').text)

I want all the 7 day temperature value which is in <element type = 'air_temperature_maximum'> for the area 'Melbourne'. Any help is much appreciated.

1 Answer 1

2

You can iterate through the XML by brute force in multiple nested loops:

from xml.etree.ElementTree import fromstring, ElementTree
from requests import get

url = 'http://www.bom.gov.au/fwo/IDV10753.xml'

req = get(url)
tree = ElementTree(fromstring(req.text))
root = tree.getroot()

for outer in root:
    if outer.tag == 'forecast':
        for inner in outer:
            if inner.attrib['description'] == 'Melbourne':
                for element in inner:
                    for temp in element:
                        if temp.attrib["type"] == 'air_temperature_maximum':
                            print(temp.text)

Which gives 7 temperatures:

23
28
42
24
22
24
27

You can also store the temperatures in a list using a list comprehension:

for outer in root:
    if outer.tag == "forecast":
        for inner in outer:
            if inner.attrib["description"] == "Melbourne":
                temps = [
                    temp.text
                    for element in inner
                    for temp in element
                    if temp.attrib["type"] == "air_temperature_maximum"
                ]
                print(temps)

List of temperatures:

['23', '28', '42', '24', '22', '24', '27']

I'll leave the end conversion of these temperatures to you.

Sign up to request clarification or add additional context in comments.

2 Comments

it's like you read my mind. I was thinking how to convert that into a list. You're a legend mate! Thank you.
@Bharath No worries man. Your question was clear and understandable, and I immediately thought showing a list example would be beneficial to you. When good questions are asked, good answers always come :).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.