Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/xml/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在python中解析yahoo weather xml时出错_Python_Xml_Django_Ubuntu_Yahoo Weather Api - Fatal编程技术网

在python中解析yahoo weather xml时出错

在python中解析yahoo weather xml时出错,python,xml,django,ubuntu,yahoo-weather-api,Python,Xml,Django,Ubuntu,Yahoo Weather Api,我一直在寻找解决方案,因此我试图在我的数据库中获取位置id的天气信息,这意味着使用模型中的位置id,并将信息存储在我的数据库中的天气日志模型中这是代码和错误如下: ![# -*- coding: UTF-8 -*- import urllib from xml.dom import minidom from xml.dom.minidom import parse from argparse import ArgumentParser from ppri

我一直在寻找解决方案,因此我试图在我的数据库中获取位置id的天气信息,这意味着使用模型中的位置id,并将信息存储在我的数据库中的天气日志模型中这是代码和错误如下:

 ![# -*- coding: UTF-8 -*-
    import urllib
    from xml.dom import minidom
    from xml.dom.minidom import parse
    from argparse import ArgumentParser
    from pprint import pprint
    from datetime import datetime

    from django.db import models
    from django.core.management.base import NoArgsCommand

    Location = models.get_model("weatherapp", "Location")
    WeatherLog = models.get_model("weatherapp", "WeatherLog")

    SILENT, NORMAL, VERBOSE = 0, 1, 2

    WEATHER_URL = 'http://weather.yahooapis.com/forecastrss?p=%s&u=c'
    METRIC_PARAMETER = ''
    WEATHER_NS = "http://xml.weather.yahoo.com/ns/rss/1.0"

    def weather_for_location(location_id, options):
        # taken from http://developer.yahoo.com/python/python-xml.html
        # and modified a little
        url = WEATHER_URL % location_id


        try:
            dom = minidom.parse(urllib.urlopen(url))
        except Exception:
            return None


     # Get the units of the current feed.
        yunits = dom.getElementsByTagNameNS(WEATHER_NS, 'units') \[0\]


        # Get the location of the specified location code.
        ylocation = dom.getElementsByTagNameNS(WEATHER_NS, 'location') \[0\]

        # Get the current conditions.
        ycondition = dom.getElementsByTagNameNS(WEATHER_NS, 'condition') \[0\]

        forecasts = \[\]
        for node in enumerate( dom.getElementsByTagNameNS(WEATHER_NS, 'forecast')):
               forecasts.append({
                    'date': node.getAttribute('date'),
                    'low': node.getAttribute('low'),
                    'high': node.getAttribute('high'),
                    'condition': node.getAttribute('text')
               })

        return {
            'current_condition': ycondition.getAttribute('text'),
            'current_temp': ycondition.getAttribute('temp'),
            'current_humidity': yatmosphere.getAttribute('humidity'),
            'current_visibility': yatmosphere.getAttribute('visibility'),
            'current_wind_speed': ywind.getAttribute('speed'),
            'forecasts': forecasts,
            'title': dom.getElementsByTagName('title')\[0\].firstChild.data,
            'guid': dom.getElementsByTagName('guid')\[0\].firstChild.data,
        }            

    class Command(NoArgsCommand):
        help = "Aggregates data from weather feed"
        def handle_noargs(self, **options):
            verbosity = int(options.get('verbosity', NORMAL))

            created_count = 0
            for l in Location.objects.all():
                weather = weather_for_location(l.location_id, options)
                if verbosity > NORMAL:
                    pprint(weather)
                timestamp_parts = map(int, weather\['guid'\].split("_")\[1:-1\])
                timestamp = datetime(*timestamp_parts)
                log, created = WeatherLog.objects.get_or_create(
                     location=l,
                     timestamp=timestamp,
                     defaults={
                        'temperature': weather\['current_temp'\],
                        'humidity': weather\['current_humidity'\],
                        'wind_speed': weather\['current_wind_speed'\],
                        'visibility': weather\['current_visibility'\],
                        }
                     )
                if created:
                    created_count += 1
            if verbosity > NORMAL:
                print "New weather logs: %d" % created_count][1]
错误:

> File
> "/home/temi/rapidsmstuts/myapp/weatherapp/management/commands/check_weather.py",
> line 74, in handle_noargs
>     timestamp_parts = map(int, weather['guid'].split("_")[1:-1]) TypeError: 'NoneType' object has no attribute '__getitem__'


File "/home/temi/rapidsmstuts/myapp/weatherapp/management/commands/check_weather.py", line 47, in weather_for_location
    'date': node.getAttribute('date'),
AttributeError: 'tuple' object has no attribute 'getAttribute'




File "/home/temi/rapidsmstuts/myapp/weatherapp/management/commands/check_weather.py", line 35, in weather_for_location
    yunits = dom.getElementsByTagNameNS(WEATHER_NS, 'units') [0]
IndexError: list index out of range

这似乎是一种非常冗长的做法。“你可能想去看看,”马修,谢谢,我从没听说过。请了解如何在本代码中使用它。文档位于-我将开始there@MatthewDaly很抱歉回到你的第一条评论,请你解释一下你所说的非常冗长的方式是什么意思。thanksIt在我看来,您必须编写大量代码来获取和解析XML,而feedparser将更轻松地为您完成这项工作