Python3 XML 获取雅虎天气的实现方法


Posted in Python onFebruary 01, 2018

参考廖雪峰的Python教程,实现Linux Python3获取雅虎天气

#!/usr/bin/env python3
# coding: utf-8
import os
from datetime import datetime
from urllib import request 
from xml.parsers.expat import ParserCreate 
file_name = "weather.txt"
for root, dirs, files in os.walk("."):
 if file_name in files:
  os.remove(os.path.join(root, file_name))
def yahoo_weather(data):
 flag = False
 weather = {"city": "", "pubdate": "", "forecast": []}
 def start_element(name, attrs):
  if name == "yweather:location":
   weather["city"] = weather["city"] + attrs["city"]
   weather["city"] = weather["city"] + " " + attrs["country"]
  if name == "yweather:forecast":
   forecast = {}
   forecast["date"] = attrs["date"]
   forecast["day"] = attrs["day"]
   forecast["high"] = attrs["high"]
   forecast["low"] = attrs["low"]
   forecast["text"] = attrs["text"]
   weather["forecast"].append(forecast)
  if name == "pubDate":
   nonlocal flag
   flag = True
  
 def char_data(text):
  nonlocal flag
  if flag:
   weather["pubdate"] = text
   flag = False
 parser = ParserCreate()
 parser.StartElementHandler = start_element
 parser.CharacterDataHandler = char_data
 parser.Parse(data)
 return weather
def print_weather(weather):
 with open(file_name, "a") as f:
  s = "City: %s\nPub date: %s" %(weather["city"], weather["pubdate"])
  print("%s" %(weather["city"]))
  f.write(s + "\n")
  for forecast in weather["forecast"]:
   date = datetime.strptime(forecast["date"], "%d %b %Y").strftime("%Y-%m-%d")
   s = "Date: %s High: %s Low: %s Weather: %s" %(date, forecast["high"], forecast["low"], forecast["text"])
   f.write(s + "\n")
  f.write("\n")
citys = ["2151330", "2151849", "44418", "615702", "2514815"]
for city in citys:
 url = "https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20weather.forecast%20where%20woeid%20%3D%20"
 url = url + city
 url = url + "&format=xml"
 with request.urlopen(url, timeout=4) as f:
  weather = yahoo_weather(f.read())
  print_weather(weather)
print("weather conditions has written to %s" %(file_name))

以上这篇Python3 XML 获取雅虎天气的实现方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持三水点靠木。

Python 相关文章推荐
Python列表生成器的循环技巧分享
Mar 06 Python
分析Python编程时利用wxPython来支持多线程的方法
Apr 07 Python
Python中的random()方法的使用介绍
May 15 Python
python制作爬虫并将抓取结果保存到excel中
Apr 06 Python
Python常用的内置序列结构(列表、元组、字典)学习笔记
Jul 08 Python
利用numpy和pandas处理csv文件中的时间方法
Apr 19 Python
Python并发:多线程与多进程的详解
Jan 24 Python
Python实现去除列表中重复元素的方法总结【7种方法】
Feb 16 Python
Python3操作MongoDB增册改查等方法详解
Feb 10 Python
pytorch:model.train和model.eval用法及区别详解
Feb 20 Python
pandas读取csv文件提示不存在的解决方法及原因分析
Apr 21 Python
tensorflow 大于某个值为1,小于为0的实例
Jun 30 Python
Python命令行解析模块详解
Feb 01 #Python
python2.7到3.x迁移指南
Feb 01 #Python
Python Paramiko模块的使用实际案例
Feb 01 #Python
python中使用xlrd读excel使用xlwt写excel的实例代码
Jan 31 #Python
python使用tensorflow保存、加载和使用模型的方法
Jan 31 #Python
python通过elixir包操作mysql数据库实例代码
Jan 31 #Python
Django视图和URL配置详解
Jan 31 #Python
You might like
fleaphp下不确定的多条件查询的巧妙解决方法
2008/09/11 PHP
Composer设置忽略版本匹配的方法
2016/04/27 PHP
php封装db类连接sqlite3数据库的方法实例
2017/12/19 PHP
TP5框架使用QueryList采集框架爬小说操作示例
2020/03/26 PHP
js 关键词高亮(根据ID/tag高亮关键字)案例介绍
2013/01/21 Javascript
js中的replace方法使用介绍
2013/10/28 Javascript
SyntaxHighlighter 3.0.83使用笔记
2015/01/26 Javascript
AngularJS快速入门
2015/04/02 Javascript
jQuery实现标题有打字效果的焦点图代码
2015/11/16 Javascript
判断JS对象是否拥有某属性的方法推荐
2016/05/12 Javascript
jQuery Ajax 上传文件处理方式介绍(推荐)
2016/06/30 Javascript
Three.js学习之Lamber材质和Phong材质
2016/08/04 Javascript
微信小程序 获取相册照片实例详解
2016/11/16 Javascript
使用JS批量选中功能实现更改数据库中的status状态值(批量展示)
2016/11/22 Javascript
webpack 4.0.0-beta.0版本新特性介绍
2018/02/10 Javascript
对angular2中的ngfor和ngif指令嵌套实例讲解
2018/09/12 Javascript
js实现数据导出为EXCEL(支持大量数据导出)
2020/03/31 Javascript
Vue页面渲染中key的应用实例教程
2021/01/12 Vue.js
js面向对象方式实现拖拽效果
2021/03/03 Javascript
python 调用c语言函数的方法
2017/09/29 Python
Python+selenium 获取一组元素属性值的实例
2018/06/22 Python
Python计算库numpy进行方差/标准方差/样本标准方差/协方差的计算
2018/12/28 Python
在pycharm中使用git版本管理以及同步github的方法
2019/01/16 Python
pandas 对日期类型数据的处理方法详解
2019/08/08 Python
python安装本地whl的实例步骤
2019/10/12 Python
Python+OpenCV检测灯光亮点的实现方法
2020/11/02 Python
Python3+PyCharm+Django+Django REST framework配置与简单开发教程
2021/02/16 Python
HTML5中的音频和视频媒体播放元素小结
2016/01/29 HTML / CSS
美国隐形眼镜网:Major Lens
2018/02/09 全球购物
外企财务年会演讲稿
2014/01/03 职场文书
十佳大学生村官事迹
2014/01/09 职场文书
《口技》教学反思
2014/02/21 职场文书
品牌推广活动策划方案
2014/08/19 职场文书
介绍信样本
2015/01/31 职场文书
2015年班级工作总结范文
2015/04/03 职场文书
撤回我也能看到!教你用Python制作微信防撤回脚本
2021/06/11 Python