python获得天气

#! /usr/bin/python
# -*- coding: cp936 -*-
# coding = utf-8

# ToDo: get weather info from weather.com.cn
# Author: Steven
# Date: 2013/05/13

import urllib2
import json

# get weather html and parse to json
weatherHtml = urllib2.urlopen('http://m.weather.com.cn/data/101200101.html').read()
weatherJSON = json.JSONDecoder().decode(weatherHtml)
weatherInfo = weatherJSON['weatherinfo']

# print weather info
print '城市:\t', weatherInfo['city']
print '时间:\t', weatherInfo['date_y']
print '24小时天气:'
print '温度:\t', weatherInfo['temp1']
print '天气:\t', weatherInfo['weather1']
print '风速:\t', weatherInfo['wind1']
print '紫外线:\t', weatherInfo['index_uv']
print '穿衣指数:\t', weatherInfo['index_d']
print '48小时天气:'
print '温度:\t', weatherInfo['temp2']
print '天气:\t', weatherInfo['weather2']
print '风速:\t', weatherInfo['wind2']
print '紫外线:\t', weatherInfo['index48_uv']
print '穿衣指数:\t', weatherInfo['index48_d']
print '72小时天气:'
print '温度:\t', weatherInfo['temp3']
print '天气:\t', weatherInfo['weather3']
print '风速:\t', weatherInfo['wind3']


http://g.kehou.com/t1029846752.html


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
首先,你需要安装一些库,比如requests、beautifulsoup4、pandas和matplotlib。你可以使用以下命令安装它们: ``` pip install requests beautifulsoup4 pandas matplotlib ``` 然后,你需要从一个天气网站上爬取数据。这里我们以中国天气网为例,使用requests和BeautifulSoup来获取数据: ```python import requests from bs4 import BeautifulSoup url = 'http://www.weather.com.cn/weather/101010100.shtml' res = requests.get(url) res.encoding = 'utf-8' soup = BeautifulSoup(res.text, 'html.parser') ``` 接下来,我们需要从页面中提取出我们需要的数据,比如天气、温度、风力等。你可以使用Chrome浏览器的“检查”功能来查看页面中这些数据的位置和标签,然后使用BeautifulSoup来提取数据。 ```python # 获取城市名 city = soup.select('.crumbs a')[-1].text.strip() # 获取天气信息 weather = [i.text.strip() for i in soup.select('.t .wea')] # 获取温度信息 temp = [i.text.strip() for i in soup.select('.t .tem')] # 获取风力信息 wind = [i.text.strip() for i in soup.select('.t .win')] # 获取日期信息 date = [i.text.strip() for i in soup.select('.t .day')] ``` 接下来,我们将这些数据存储在一个pandas的DataFrame中,并进行可视化。这里我们使用matplotlib库来绘制图表。 ```python import pandas as pd import matplotlib.pyplot as plt # 存储数据 data = pd.DataFrame({ '日期': date, '天气': weather, '温度': temp, '风力': wind }) # 绘制温度折线图 plt.plot(data['日期'], data['温度']) plt.title(f'{city}未来5天温度变化') plt.xlabel('日期') plt.ylabel('温度(℃)') plt.show() ``` 这样就可以得到一个简单的温度折线图了。你可以根据需要继续优化和完善代码。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值