怎么用脚本获取天气预警

wen 实用脚本 3

本文目录导读:

怎么用脚本获取天气预警

  1. 使用高德地图API(推荐)
  2. 使用气象局官方API
  3. 使用第三方API(和风天气)
  4. 简易的爬虫方案(中国天气网)
  5. 使用建议
  6. 实现完整示例(含配置)
  7. 注意事项

使用高德地图API(推荐)

import requests
import json
def get_weather_alert_gaode(adcode='110000'):
    """
    获取天气预警信息
    adcode: 行政区划代码,如北京=110000
    """
    # 需要注册高德地图开发者账号获取key
    key = '你的高德API_KEY'
    url = f'https://restapi.amap.com/v3/weather/weatherInfo'
    params = {
        'key': key,
        'city': adcode,
        'extensions': 'all'  # all返回详细天气+预警
    }
    response = requests.get(url, params=params)
    data = response.json()
    if data.get('status') == '1':
        # 获取预警信息
        alerts = data.get('lives', [{}])[0]
        print(f"城市: {alerts.get('province')} {alerts.get('city')}")
        print(f"天气: {alerts.get('weather')}")
        print(f"温度: {alerts.get('temperature')}°C")
        # 预警信息在另一个字段
        warnings = data.get("forecasts", [{}])[0].get("cast", [])
        return data
    return None
get_weather_alert_gaode()

使用气象局官方API

import requests
import xml.etree.ElementTree as ET
def get_weather_alert_cma(province='北京', city='北京'):
    """
    使用中国气象局预警信息
    """
    # 中国天气网预警接口
    url = 'http://www.weather.com.cn/weatheralarm/js/北京.json'
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
    }
    try:
        response = requests.get(url, headers=headers)
        if response.status_code == 200:
            data = response.json()
            # 解析预警信息
            for item in data.get('alerts', []):
                print(f"预警类型: {item.get('type')}")
                print(f"预警等级: {item.get('level')}")
                print(f"预警内容: {item.get('title')}")
                print(f"发布时间: {item.get('time')}")
                print("-" * 40)
    except Exception as e:
        print(f"请求失败: {e}")
get_weather_alert_cma()

使用第三方API(和风天气)

import requests
def get_weather_alert_heweather(city_id='101010100'):
    """
    使用和风天气API
    city_id: 城市ID,如北京=101010100
    """
    # 注册和风天气获取你的key
    api_key = '你的API_KEY'
    # 预警API
    url = 'https://devapi.qweather.com/v7/warning/now'
    params = {
        'location': city_id,
        'key': api_key,
        'lang': 'zh'
    }
    response = requests.get(url, params=params)
    data = response.json()
    if data.get('code') == '200':
        for warning in data.get('warning', []):
            print(f"预警类型: {warning['typeName']}")
            print(f"预警等级: {warning['level']}")
            print(f"预警文本: {warning['text']}")
            print(f"发布时间: {warning['pubTime']}")
            print("-" * 40)
    else:
        print(f"查询失败: {data.get('message')}")
get_weather_alert_heweather()

简易的爬虫方案(中国天气网)

import requests
from bs4 import BeautifulSoup
def get_weather_alert_scrape(city_name='北京'):
    """
    从中国天气网爬取预警信息
    """
    url = f'http://www.weather.com.cn/weatheralarm/{city_name}/'
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
    }
    response = requests.get(url, headers=headers)
    soup = BeautifulSoup(response.text, 'html.parser')
    # 查找预警信息对象
    alert_items = soup.select('.alarm-list li')
    for item in alert_items[:5]:  # 只取前5条
        title = item.select_one('.alarm-title')
        date = item.select_one('.alarm-date')
        if title:
            print(f"预警: {title.text.strip()}")
            print(f"时间: {date.text.strip() if date else '未知'}")
            print("-" * 30)
get_weather_alert_scrape()

使用建议

  1. 推荐使用高德地图API - 免费且稳定
  2. 和风天气 - 支持更多的数据维度
  3. 中国天气网 - 官方数据,但需要注意反爬策略

实现完整示例(含配置)

import requests
import json
import time
class WeatherAlertSystem:
    def __init__(self, gaode_key=None, heweather_key=None):
        self.gaode_key = gaode_key
        self.heweather_key = heweather_key
    def get_gaode_alert(self, adcode):
        """高德预警"""
        url = 'https://restapi.amap.com/v3/weather/weatherInfo'
        params = {
            'key': self.gaode_key,
            'city': adcode,
            'extensions': 'all'
        }
        data = requests.get(url, params=params).json()
        return data
    def check_alerts(self, province, city):
        """综合检查预警"""
        alerts = []
        try:
            # 简单模拟
            print(f"正在获取{province}{city}的天气预警...")
            # 这里调用上述任一方法
        except Exception as e:
            print(f"获取失败: {e}")
        return alerts
    def monitor(self, province, city, interval=600):
        """定时监控天气预警"""
        while True:
            self.check_alerts(province, city)
            time.sleep(interval)  # 默认每10分钟检查一次
# 使用示例
monitor = WeatherAlertSystem()
monitor.check_alerts('北京', '北京')

注意事项

  1. 需要注册相应API平台的开发者账号
  2. 注意API调用频率限制
  3. 生产环境建议添加错误重试机制
  4. 定期更新API密钥和权限

选择哪种方案取决于你的具体需求和使用场景,最简单的方式是使用高德API,接口稳定且文档完善。

抱歉,评论功能暂时关闭!