Discuss / Python / 简单版本

简单版本

Topic source
def parseXml(xml_str):
    data = {'city': '', 'forecast': []}

    def start_element(name, attrs):
        print(name)
        if name == 'yweather:location' and 'city' in attrs:
            data['city'] = attrs['city']
        elif name == 'yweather:forecast' and 'date' in attrs and 'high' in attrs and 'low' in attrs:
            data['forecast'].append({'date': attrs['date'], 'high': attrs['high'], 'low': attrs['low']})

    parser = ParserCreate()
    parser.StartElementHandler = start_element
    parser.Parse(xml_str)
    return data

忘记格式化日期了

from xml.parsers.expat import ParserCreate
from urllib import request
from datetime import datetime

def parseXml(xml_str):
    data = {'city': '', 'forecast': []}

    def start_element(name, attrs):
        print(name)
        if name == 'yweather:location' and 'city' in attrs:
            data['city'] = attrs['city']
        elif name == 'yweather:forecast' and 'date' in attrs and 'high' in attrs and 'low' in attrs:
            data['forecast'].append({'date': datetime.strptime(attrs['date'], '%d %b %Y').strftime('%Y-%m-%d'), 'high': attrs['high'], 'low': attrs['low']})

    parser = ParserCreate()
    parser.StartElementHandler = start_element
    parser.Parse(xml_str)
    return data

  • 1

Reply