【问题标题】:Weather Underground Parsing Python天气地下解析 Python
【发布时间】:2017-04-27 15:35:08
【问题描述】:

我正在尝试按天分离天气地下 API 的代码。目前,我可以获取 forecastday 的数组,但无法获取 fcttext 和 title 的每个数组。这是迄今为止我在 python 中的代码和我想要提取的数据:

import requests
from pprint import pprint
import json

r = requests.get("http://api.wunderground.com/api/id/forecast10day/q/CA/San_Francisco.json")
data = r.json()
pprint (data['forecast']['txt_forecast']['forecastday'])


"forecastday": [
    {
    "period":0,
    "icon":"partlycloudy",
    "icon_url":"http://icons.wxug.com/i/c/k/partlycloudy.gif",
    "title":"Thursday",
    "fcttext":"Cloudy early with peeks of sunshine expected late. High 54F. Winds W at 10 to 20 mph.",
    "fcttext_metric":"Cloudy skies early, then partly cloudy this afternoon. High 12C. Winds W at 15 to 30 km/h.",
    "pop":"0"
    }
    ,
    {
    "period":1,
    "icon":"nt_mostlycloudy",
    "icon_url":"http://icons.wxug.com/i/c/k/nt_mostlycloudy.gif",
    "title":"Thursday Night",
    "fcttext":"Partly cloudy this evening, then becoming cloudy after midnight. Low 38F. Winds N at 5 to 10 mph.",
    "fcttext_metric":"Partly cloudy early followed by cloudy skies overnight. Low 3C. Winds N at 10 to 15 km/h.",
    "pop":"0"
    }
    ,
    {
    "period":2,
    "icon":"chancerain",
    "icon_url":"http://icons.wxug.com/i/c/k/chancerain.gif",
    "title":"Friday",
    "fcttext":"Light rain early...then remaining cloudy with showers in the afternoon. High 52F. Winds NE at 10 to 15 mph. Chance of rain 60%.",
    "fcttext_metric":"Light rain early...then remaining cloudy with showers in the afternoon. High 11C. Winds NE at 15 to 25 km/h. Chance of rain 60%.",
    "pop":"60"
    }

【问题讨论】:

    标签: python json api parsing web-scraping


    【解决方案1】:

    data['forecast']['txt_forecast']['forecastday'] 中的值是一个字典列表。因此,您需要遍历该列表以从中取出项目。

    for forecastday in data['forecast']['txt_forecast']['forecastday']:
        print(forecastday['title'])
        print(forecastday['fcttext'])
    

    生产:

    Thursday
    Cloudy early with peeks of sunshine expected late. High 54F. Winds W at 10 to 20 mph.
    etc...
    

    【讨论】:

    • 谢谢!完美运行。
    猜你喜欢
    • 1970-01-01
    • 2020-01-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-24
    • 1970-01-01
    • 2013-10-25
    相关资源
    最近更新 更多