4行Python代码获取所在城市天气预报

https://zhuanlan.zhihu.com/p/26369491

import requests

r = requests.get('http://www.weather.com.cn/data/sk/101020100.html')

r.encoding = 'utf-8'

print (r.json()'weatherinfo', r.json()'weatherinfo', r.json()'weatherinfo')

https://blog.csdn.net/weixin_46089319/article/details/103821688?utm_medium=distribute.pc_relevant.none-task-blog-2~default~baidujs_baidulandingword~default-0.control&spm=1001.2101.3001.4242

import requests

1、发送请求,获取数据

url = f'http://wthrcdn.etouch.cn/weather_mini?citykey=101282104'
res = requests.get(url)
res.encoding = 'utf-8'

res_json = res.json()

2、数据格式化

data = res_json['data']
city = f"城市:{data['city']}"

字符串格式化的一种方式 f"{}" 通过字典传递值

today = data'forecast'
date = f"日期:{today['date']}"

换行

now = f"实时温度:{data['wendu']}度"
temperature = f"温度:{today['high']} {today['low']}"
fengxiang = f"风向:{today['fengxiang']}"
wtype = f"天气:{today['type']}"
tips = f"贴士:{data['ganmao']}"

result = city+";" + date +";" + now +";n" + temperature +";" + fengxiang+";" + wtype +";n" + tips

print(result)

发表新评论