python 爬取天气信息

本文介绍了一个使用Python请求OpenWeatherMap API获取武汉天气预报数据的示例代码。通过解析返回的JSON数据,提取了城市名称、天气状况、气温、气压和时间等关键信息,并展示了如何遍历和打印所有预报数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

url:http://api.openweathermap.org/data/2.5/forecast?q=wuhan&mode=json&units=metric&lang=zh_cn&APPID=6a67ed641c0fda8b69715c43518b6996

代码:

 

import urllib.request as req
import json

weather_url = "http://api.openweathermap.org/data/2.5/forecast?q=wuhan&mode=json&units=metric&lang=zh_cn&APPID=6a67ed641c0fda8b69715c43518b6996"

result = req.urlopen(weather_url).read().decode("utf-8")
print(result)
# 将字符串转换成json对象
result_json = json.loads(result)
print("="*30)

city = result_json['city']['name']
time = result_json['list'][0]['dt_txt']
weather = result_json['list'][0]['weather'][0]['description']
wind = result_json['list'][0]['wind']['speed']
temp = result_json['list'][0]['main']['temp']
pressure = result_json['list'][0]['main']['pressure']

len1 = len(result_json['list'])

for i in range(0,len1):
    print("城市名称:%s,天气:%s,气温:%s,气压:%s,时间:%s" %(result_json['city']['name'],result_json['list'][i]['weather'][0]['description'],str(result_json['list'][i]['main']['temp']),str(result_json['list'][i]['main']['pressure']),str(result_json['list'][i]['dt_txt'])))

 

运行截图:

 

<think>好的,我需要帮用户提供一个Python爬取天气信息的代码示例。用户之前已经问过相关的问题,我的回答里包含了使用requests和BeautifulSoup的示例,现在用户再次请求代码示例,可能需要更详细的说明或者不同的数据源。 首先,查看用户提供的引用内容,引用1到5提到了不同的方法,包括爬取中国天气网、保存为CSV、可视化分析等。用户现在明确需要代码示例,可能希望更具体的实现,比如完整的爬取流程或者如何处理数据。 考虑到用户之前的问题中,我给出了一个简单的例子,但用户可能需要更完整的代码,包含错误处理、数据存储等。另外,引用2和4提到将数据保存为CSV,并进行可视化,所以用户可能希望代码包含这些部分。 需要确保代码符合用户的需求,比如爬取中国天气网的数据,使用requests和BeautifulSoup,然后存储到CSV。同时,用户可能需要知道如何解析不同的数据,比如温度、湿度等。 另外,用户可能关心反爬机制,比如设置User-Agent,处理可能的异常,比如网络请求失败或元素未找到的情况。在之前的回答中,我提到了需要添加健壮性和异常处理,所以应该在代码中体现这一点。 还要注意引用中的内容,比如引用3和4提到使用pandas处理数据,matplotlib和pyecharts进行可视化。用户可能需要代码示例中包含这些步骤,但当前问题主要询问爬取代码,所以可能先提供爬取和存储的部分,再简要提及可视化。 需要检查中国天气网的结构是否有变化,之前的示例代码可能基于旧的HTML结构,需要确保选择正确的CSS选择器或类名。可能需要查看中国天气网的页面结构,确保示例代码的有效性。 最后,用户可能需要知道如何运行代码,比如安装必要的库(requests, BeautifulSoup, pandas),所以应该在代码前注明安装命令。同时,需要处理可能出现的编码问题,比如网页编码为UTF-8或GBK,确保正确解析。 总结步骤:导入库、发送请求、解析HTML、提取数据、存储到CSV、异常处理、可视化示例。确保代码结构清晰,注释详细,方便用户理解和修改。</think>### Python爬取天气信息代码示例(基于中国天气网) #### 一、核心步骤与完整代码 ```python import requests from bs4 import BeautifulSoup import pandas as pd from datetime import datetime def fetch_weather(city_code="101010100"): # 北京城市代码 url = f"http://www.weather.com.cn/weather/{city_code}.shtml" # 模拟浏览器访问 headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) ' 'AppleWebKit/537.36 (KHTML, like Gecko) ' 'Chrome/119.0.0.0 Safari/537.36', 'Referer': 'http://www.weather.com.cn/' } try: response = requests.get(url, headers=headers, timeout=10) response.encoding = 'utf-8' # 显式指定编码 soup = BeautifulSoup(response.text, 'lxml') # 定位天气数据容器 weather_box = soup.find('ul', class_='t clearfix') if not weather_box: raise ValueError("天气数据容器未找到") # 解析当天数据 today_data = weather_box.find('li', class_='on') date = today_data.find('h1').get_text().strip() weather = today_data.find('p', class_='wea').get_text().strip() temp = today_data.find('p', class_='tem').get_text().replace('\n', '') wind = today_data.find('p', class_='win').find('i').get_text().strip() # 存储数据 data = { '城市': get_city_name(city_code), '日期': f"{datetime.now().year}-{date}", '天气': weather, '温度': temp, '风力': wind } return data except Exception as e: print(f"抓取失败: {str(e)}") return None def get_city_name(code): # 城市代码映射表(部分示例) city_map = { "101010100": "北京", "101020100": "上海", "101280101": "广州" } return city_map.get(code, "未知城市") def save_to_csv(data, filename='weather.csv'): df = pd.DataFrame([data]) df.to_csv(filename, mode='a', header=not pd.io.common.file_exists(filename), index=False) if __name__ == "__main__": result = fetch_weather("101020100") # 上海 if result: save_to_csv(result) print(f"数据已保存:\n{result}") ``` #### 二、关键功能说明 1. **城市代码机制** 中国天气网使用特定城市编码(如北京101010100),可通过[国家气象信息中心](http://www.nmc.cn/)查询完整编码表[^2] 2. **反爬策略处理** - 添加`User-Agent`模拟浏览器 - 设置`Referer`头降低封禁风险 - 使用`timeout`防止请求阻塞 3. **数据持久化** 采用追加模式写入CSV文件,支持多批次数据采集[^4] #### 三、进阶可视化示例 ```python # 可视化分析(需先积累数据) import matplotlib.pyplot as plt def plot_temperature(): df = pd.read_csv('weather.csv') df['日期'] = pd.to_datetime(df['日期']) plt.figure(figsize=(12,6)) df['温度'].str.extract('(-?\d+)/(-?\d+)℃').astype(float).mean(axis=1).plot() plt.title('温度变化趋势') plt.xlabel('日期') plt.ylabel('平均温度(℃)') plt.grid(True) plt.show() # plot_temperature() # 取消注释运行 ``` #### 四、运行准备 ```bash # 安装依赖库 pip install requests beautifulsoup4 pandas matplotlib ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值