树莓派使用Python3获取天气信息

一.运行环境

不必使用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

你可能感兴趣的:(树莓派)