【问题标题】:Web scraping national weather API difficulty getting correct format in PythonWeb 抓取国家天气 API 难以在 Python 中获取正确格式
【发布时间】:2021-09-12 04:15:57
【问题描述】:

我正在尝试从此链接“https://api.weather.gov/gridpoints/MFL/44,66”中抓取数据并将其转换为正确的格式。这就是挑战:

在此作业中,您应该编写一个函数(名为 gets_temperature_forecast()),该函数获取地址/城市并返回来自国家气象局的温度预报(摄氏度和华氏度)。函数输出应如下所示:

****Date: 2019-07-04 Time: 08:00:00 Temperature: 27.22 C (81.0 F)**** #with the little circle on top etc

在尝试格式化之前看起来像这样

{'validTime': '2021-09-11T21:00:00+00:00/PT2H', 'value': 29.444444444444443}, {'validTime': '2021-09-11T23:00:00+00:00/PT1H', 'value': 28.333333333333332}, 

我在这个平台上研究了很多问题,但仍然遇到问题。我似乎无法正确格式化数据,当我尝试提取时间时,我无法成功将其转换为常规时间,而且我的最后一行代码不起作用。我想我可能需要使用 datetime 函数来删除日期,但是我无法转换它。摄氏温度相同,以正确格式化 C 和 F。

任何帮助将不胜感激!

这是我的代码:

import datetime
import pandas as pd
import requests
import json

url = "https://api.weather.gov/gridpoints/MFL/44,66"

response = requests.get(url).json()
print(response) #checking to see i have the URL

data_cleaned = []

for time in response ['data']['values']: #here is where everything gets messed up 
    data_cleaned.append({
       'Date': time['validTime'],
       'Time': (time['T']),
       'Temperature': time['value'], (time['value']*1.8) + 32
        })
 

【问题讨论】:

  • 好的,所以现在我遇到了这个问题:响应中的项目“我得到一个错误字符串索引必须是整数”["properties"]: date = item["validTime"] time = item[ "有效时间"] 温度 = 项目["值"]
  • edit更新您的问题。

标签: python web-scraping format weather


【解决方案1】:

试试这个:

gets_temperature_forecast(address, city):

    url = 'https://api.weather.gov/gridpoints/MFL/44,66'
    response = requests.get(url).json()
    
    time = response['temperature']['values'][0]['validTime']
    temp = response['temperature']['values'][0]['value']
    
    print(f"Temperature: {temp}\nTime: {time}")

我希望这有助于您走上正确的道路,尽管您需要通过自己检查 API 文档来弄清楚如何使用地址/城市来获取这些统计信息。 (我知道您需要将字典附加到列表中,但我认为我向您展示的示例有望足以帮助您自己弄清楚其余部分)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-05-28
    • 2022-12-18
    • 2013-11-09
    • 1970-01-01
    • 1970-01-01
    • 2016-11-27
    • 1970-01-01
    相关资源
    最近更新 更多