树莓派使用Python3获取天气信息
2016-12-12 23:21
741 查看
一.运行环境
不必使用requests库。只需要python3自带的urllib库和json库即可。import requests r=requests.get('http://www.weather.com.cn/') r.text
实际上就等于
import urllib.request r=urllib.request.urlopen('http://www.weather.com.cn/') text=r.read() print(text)
二.获取城市代码
很多教程都是通过代码逐步询问网站来获得城市代码。这里介绍一个简单的方法。在http://www.weather.com.cn 中搜索你所要的城市。进入天气页之后,网址末尾的数字就是城市代码。
厦门天气网址是http://www.weather.com.cn/weather1d/101230201.shtml#input,这里的数字101230201就是厦门的城市代码。
将这个代码代入到以下3个网址的任意一个得到不同的天气JSON格式的信息。
http://www.weather.com.cn/data/sk/101270104.html
http://www.weather.com.cn/data/cityinfo/101270104.html
http://m.weather.com.cn/data/101270104.html
引自http://www.dfrobot.com.cn/community/thread-2662-1-1.html
三.代码
#! /usr/bin/python # coding = utf-8 import urllib.request import json ApiUrl= \ "http://www.weather.com.cn/data/sk/101230201.html" html=urllib.request.urlopen(ApiUrl) #读取并解码 data=html.read().decode("utf-8") #将JSON编码的字符串转换回Python数据结构 ss=json.loads(data) info=ss['weatherinfo'] print('城市:%s'%info['city']) print('温度:%s度'%info['temp']) print('风速:%s'%info['WD'],info['WS']) print('湿度:%s'%info['SD']) print('时间:%s'%info['time'])
结果如下:
城市:厦门 温度:16度 风速:东南风 2级 湿度:65% 时间:17:05
相关文章推荐
- [Python高效编程] - 获取天气信息并使用迭代for输出
- 树莓派使用python获取GY-85九轴模块信息
- 使用 Python 获取 Linux 系统信息
- 飘逸的python - 使用traceback获取详细的异常信息
- 【python系列】使用 BeautifulSoup 获取 meta 信息
- 使用python编写脚本获取手机当前应用的信息
- 使用Python获取Linux系统的各种信息
- 使用java获取未来7天天气信息,可用于android
- linux系统使用python获取内存使用信息脚本分享
- python使用psutil获取服务器信息
- 使用Python获取所有非偶数尺寸图片资源信息
- 使用python编写脚本获取手机当前应用apk的信息
- python调用中国天气网的公用API获取天气信息
- 使用python获取CPU和内存信息(linux系统)
- python 学习笔记 12 -- 写一个脚本获取城市天气信息
- 使用python urllib2获取网页信息
- 树莓派中python获取GY-85九轴模块信息示例
- 使用python获取CPU和内存信息的思路与实现(linux系统)
- 使用 Python 获取 Linux 系统信息的代码
- 使用Python获取Linux系统的各种信息