python3 获取天气预报api接口

直接上代码,一个接口

# http://flash.weather.com.cn/wmaps/xml/beijing.xml
# http://flash.weather.com.cn/wmaps/xml/china.xml

我就直接上代码

#coding=utf-8
# http://flash.weather.com.cn/wmaps/xml/beijing.xml
# http://flash.weather.com.cn/wmaps/xml/china.xml

from urllib import request
import urllib.parse
from xml.dom.minidom import parse
import xml.dom.minidom
import time
from lxml import etree
import requests

day = time.strftime('%Y-%m-%d',time.localtime(time.time()))

def get_china():
    province_info = request.urlopen('http://flash.weather.com.cn/wmaps/xml/china.xml')
    DOMTree = xml.dom.minidom.parse(province_info)
    province_data = DOMTree.documentElement
    # 获取所有标签为<city>的信息,即全部的省
    provinces = province_data.getElementsByTagName("city")
    provinces_area_list = []
    for province in provinces:
        china_city = {}
        # 获取省的拼音
        china_city['prov_py'] = province.getAttribute("pyName")
        # 获取省的名称
        china_city['prov_name'] = province.getAttribute("quName")
        china_city['cityname'] = province.getAttribute("cityname")
        china_city['state1'] = province.getAttribute("state1")
        china_city['state2'] = province.getAttribute("state2")
        china_city['prov_t_high'] = province.getAttribute("tem2")
        china_city['prov_t_low'] = province.getAttribute("tem1")
        china_city['prov_state'] = province.getAttribute("stateDetailed")
        china_city['prov_windstate'] = province.getAttribute("windState")
        provinces_area_list.append(china_city['prov_py'])

    return provinces_area_list
#第一种方式
def get_city(provinces_area_list):
    for xxs in provinces_area_list:
        try:
            province_info_area = request.urlopen('http://flash.weather.com.cn/wmaps/xml/%s.xml'%(xxs))
            DOMTree_area = xml.dom.minidom.parse(province_info_area)
            province_data_area = DOMTree_area.documentElement
            provinces_area = province_data_area.getElementsByTagName("city")
            for province in provinces_area:
                # 获取市
                ccity = {}
                ccity['cityname'] = province.getAttribute("cityname")
                ccity['cityX'] = province.getAttribute("cityX")
                ccity['cityY'] = province.getAttribute("cityY")
                ccity['pyName'] = province.getAttribute("pyName")
                ccity['stateDetailed'] = province.getAttribute("stateDetailed")
                ccity['tem1'] = province.getAttribute("tem1")
                ccity['tem2'] = province.getAttribute("tem2")
                ccity['windState'] = province.getAttribute("windState")
                ccity['windDir'] = province.getAttribute("windDir")
                ccity['windPower'] = province.getAttribute("windPower")
                ccity['humidity'] = province.getAttribute("humidity")
                ccity['time'] = str(day) + ' '+ str(province.getAttribute("time"))
                print(ccity)
        except Exception as e:
            print(xxs)
#第二种方式,没有完善
def get_re_city(provinces_area_list):
    provinces_area_list.remove('xisha')
    provinces_area_list.remove('nanshadao')
    provinces_area_list.remove('diaoyudao')
    for xxs in provinces_area_list:
            url = 'http://flash.weather.com.cn/wmaps/xml/%s.xml'%(xxs)
            res = requests.get(url)
            sss = res.content.decode('utf8')
            print(sss)
            sssa = sss.splitlines()
            for x in sssa:
                print(8888,x.split(' '))


# lists = get_china()
# get_city(lists)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 可以参考下面的代码示例,使用 Python获取天气预报:import requests# Get the response from OpenWeatherMap response = requests.get('http://api.openweathermap.org/data/2.5/weather?q=London,uk')# Convert the response to a Python dictionary weather_data = response.json()# Get the temperature from the dictionary temperature = weather_data['main']['temp'] ### 回答2: 获取天气预报可以使用Python的第三方库requests和json。 以下是一个简单的代码示例: ```python import requests import json def get_weather(city_name): # 设置API接口的URL和参数 url = "https://api.seniverse.com/v3/weather/daily.json" params = { "key": "your_api_key", # 替换成你的API Key "location": city_name, # 替换成要查询的城市 "language": "zh-Hans", "unit": "c" # 单位设为摄氏度 } try: # 发送GET请求获取天气数据 response = requests.get(url, params=params) data = response.json() # 解析JSON数据并提取所需天气信息 results = data["results"][0] location = results["location"]["name"] now_weather = results["daily"][0] date = now_weather["date"] text_day = now_weather["text_day"] high_temperature = now_weather["high"] low_temperature = now_weather["low"] # 打印天气信息 print(f"{location} {date}:{text_day},最高温度:{high_temperature}℃,最低温度:{low_temperature}℃") except: print("获取天气信息失败") # 输入要查询的城市并调用函数获取天气信息 city = input("请输入要查询的城市:") get_weather(city) ``` 请注意,上述示例代码使用了心知天气API接口,需要在`params`字典中填入自己的API Key才能正常使用。同时,本代码示例只获取了当天的天气信息,若需要获取更多天数的天气预报,可以修改`params`中的`start`和`days`参数。 ### 回答3: 以下是一个使用Python获取天气预报的简单代码示例: ```python import requests def get_weather_forecast(city): # 构造请求URL url = f"https://api.openweathermap.org/data/2.5/weather?q={city}&appid=YOUR_API_KEY" try: # 发送HTTP GET请求 response = requests.get(url) if response.status_code == 200: # 解析JSON响应数据 weather_data = response.json() # 提取天气信息 weather = weather_data['weather'][0]['description'] temperature = weather_data['main']['temp'] humidity = weather_data['main']['humidity'] # 打印天气预报 print(f"城市:{city}") print(f"天气:{weather}") print(f"温度:{temperature}") print(f"湿度:{humidity}") else: print("获取天气预报失败") except requests.exceptions.RequestException: print("发生网络请求错误") # 调用函数获取天气预报 get_weather_forecast("上海") ``` 以上代码使用了requests库发送HTTP GET请求,通过OpenWeatherMap API获取天气预报的JSON数据,并进行解析,打印出城市、天气、温度和湿度信息。需要替换`YOUR_API_KEY`为自己的API密钥来访问OpenWeatherMap API

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值