Python实现从百度API获取天气的方法
2019/7/13 21:34:08
本文主要是介绍Python实现从百度API获取天气的方法,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
本文实例讲述了Python实现从百度API获取天气的方法。分享给大家供大家参考。具体实现方法如下:
复制代码 代码如下:
__author__ = 'saint'
import os
import urllib.request
import urllib.parse
import json
class weather(object):
# 获取城市代码的uri
code_uri = "http://apistore.baidu.com/microservice/cityinfo?cityname="
# 获取天气信息的uri
weather_uri = "http://apistore.baidu.com/microservice/weather?cityid="
# 主处理逻辑
def mainHandle(self):
print("输入你要查询的天气:")
city_name = input()
uri = self.code_uri + urllib.parse.quote(city_name)
ret = json.loads(urllib.request.urlopen(uri).read().decode("utf8"))
if ret['errNum'] != 0:
print(ret['retMsg'])
return False
else:
weather_uri = self.weather_uri + ret['retData']['cityCode']
data = json.loads(urllib.request.urlopen(weather_uri).read().decode("utf8"))
if data['errNum'] == 0:
ret_data = data['retData']
output = "城市名:" + city_name + "\r\n"
output += "更新时间:" + ret_data["date"] + " " + ret_data["time"] + "\r\n"
output += "天气:" + ret_data["weather"] + " [" + ret_data["WD"] + ret_data["WS"] + "]\r\n"
output += "当前温度:" + ret_data["temp"] + " (" + ret_data["h_tmp"] + " ---> " + ret_data["l_tmp"] + ")\r\n"
print(output)
return True
else:
print(data['errMsg'])
return False
if __name__ == "__main__":
weather = weather()
weather.mainHandle()
import os
import urllib.request
import urllib.parse
import json
class weather(object):
# 获取城市代码的uri
code_uri = "http://apistore.baidu.com/microservice/cityinfo?cityname="
# 获取天气信息的uri
weather_uri = "http://apistore.baidu.com/microservice/weather?cityid="
# 主处理逻辑
def mainHandle(self):
print("输入你要查询的天气:")
city_name = input()
uri = self.code_uri + urllib.parse.quote(city_name)
ret = json.loads(urllib.request.urlopen(uri).read().decode("utf8"))
if ret['errNum'] != 0:
print(ret['retMsg'])
return False
else:
weather_uri = self.weather_uri + ret['retData']['cityCode']
data = json.loads(urllib.request.urlopen(weather_uri).read().decode("utf8"))
if data['errNum'] == 0:
ret_data = data['retData']
output = "城市名:" + city_name + "\r\n"
output += "更新时间:" + ret_data["date"] + " " + ret_data["time"] + "\r\n"
output += "天气:" + ret_data["weather"] + " [" + ret_data["WD"] + ret_data["WS"] + "]\r\n"
output += "当前温度:" + ret_data["temp"] + " (" + ret_data["h_tmp"] + " ---> " + ret_data["l_tmp"] + ")\r\n"
print(output)
return True
else:
print(data['errMsg'])
return False
if __name__ == "__main__":
weather = weather()
weather.mainHandle()
希望本文所述对大家的Python程序设计有所帮助。
这篇关于Python实现从百度API获取天气的方法的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-12-20Python编程入门指南
- 2024-12-20Python编程基础与进阶
- 2024-12-19Python基础编程教程
- 2024-12-19python 文件的后缀名是什么 怎么运行一个python文件?-icode9专业技术文章分享
- 2024-12-19使用python 把docx转为pdf文件有哪些方法?-icode9专业技术文章分享
- 2024-12-19python怎么更换换pip的源镜像?-icode9专业技术文章分享
- 2024-12-19Python资料:新手入门的全面指南
- 2024-12-19Python股票自动化交易实战入门教程
- 2024-12-19Python股票自动化交易入门教程
- 2024-12-18Python量化入门教程:轻松掌握量化交易基础知识