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编程之多态用法实例详解
May 19 Python
简述Python中的进程、线程、协程
Mar 18 Python
Python入门之三角函数tan()函数实例详解
Nov 08 Python
python3+PyQt5实现拖放功能
Apr 24 Python
Python 输入一个数字判断成绩分数等级的方法
Nov 15 Python
Python二叉树的遍历操作示例【前序遍历,中序遍历,后序遍历,层序遍历】
Dec 24 Python
Python Pandas实现数据分组求平均值并填充nan的示例
Jul 04 Python
pandas中DataFrame修改index、columns名的方法示例
Aug 02 Python
python实现百度OCR图片识别过程解析
Jan 17 Python
django模板获取list中指定索引的值方式
May 14 Python
python 实现网易邮箱邮件阅读和删除的辅助小脚本
Mar 01 Python
Pytorch可视化的几种实现方法
Jun 10 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
计算一段日期内的周末天数的php代码(星期六,星期日总和)
2009/11/12 PHP
关于二级目录拖拽排序的实现(源码示例下载)
2013/04/26 PHP
php中的常用魔术方法总结
2013/08/02 PHP
php实现httpclient类示例
2014/04/08 PHP
php eval函数一句话木马代码
2015/05/21 PHP
Zend Framework入门知识点小结
2016/03/19 PHP
PHP实现数据库的增删查改功能及完整代码
2018/04/18 PHP
JavaScript 替换Html标签实现代码
2009/10/14 Javascript
JavaScript在IE和Firefox(火狐)的不兼容问题解决方法小结
2010/04/13 Javascript
最新28个很棒的jQuery 教程
2011/05/28 Javascript
Javascript OOP之面向对象
2016/07/31 Javascript
JS闭包可被利用的常见场景小结
2017/04/09 Javascript
浅谈Vuex的状态管理(全家桶)
2017/11/04 Javascript
微信小程序表单验证form提交错误提示效果
2020/06/19 Javascript
在antd Form表单中select设置初始值操作
2020/11/02 Javascript
python使用cStringIO实现临时内存文件访问的方法
2015/03/26 Python
python正则表达式之作业计算器
2016/03/18 Python
centos6.4下python3.6.1安装教程
2017/07/21 Python
基于Python中numpy数组的合并实例讲解
2018/04/04 Python
Python使用matplotlib绘制三维图形示例
2018/08/25 Python
对python dataframe逻辑取值的方法详解
2019/01/30 Python
如何在Python中实现goto语句的方法
2019/05/18 Python
pytorch索引查找 index_select的例子
2019/08/18 Python
TensorFlow中如何确定张量的形状实例
2020/06/23 Python
浅谈HTML5 defer和async的区别
2016/06/07 HTML / CSS
德国价格合理的品牌商品购物网站:averdo
2019/03/21 全球购物
美国珠宝精品店:Opulent Jewelers
2019/08/20 全球购物
九月份红领巾广播稿
2014/01/22 职场文书
学习教师法的心得体会
2014/09/03 职场文书
简单租房协议书(范本)
2014/10/13 职场文书
四十年同学聚会致辞
2015/07/28 职场文书
大学迎新生欢迎词
2015/09/29 职场文书
2016年社会主义核心价值观心得体会
2016/01/21 职场文书
Windows安装Anaconda3的方法及使用过程详解
2021/06/11 Python
Winsows11性能如何? win11性能测评多核竟比Win10差了10%
2021/11/21 数码科技
Python pyecharts案例超市4年数据可视化分析
2022/08/14 Python