树莓派使用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
  • 2
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值