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

yipeiwu_com5年前Python基础

参考廖雪峰的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设计】。

相关文章

关于pytorch中网络loss传播和参数更新的理解

关于pytorch中网络loss传播和参数更新的理解

相比于2018年,在ICLR2019提交论文中,提及不同框架的论文数量发生了极大变化,网友发现,提及tensorflow的论文数量从2018年的228篇略微提升到了266篇,keras从...

pyv8学习python和javascript变量进行交互

python取得javascript里面的值 复制代码 代码如下:import PyV8 with PyV8.JSContext() as env1:   ...

Python中矩阵库Numpy基本操作详解

NumPy是一个关于矩阵运算的库,熟悉Matlab的都应该清楚,这个库就是让python能够进行矩阵话的操作,而不用去写循环操作。 下面对numpy中的操作进行总结。 numpy包含...

Django卸载之后重新安装的方法

前言 大家应该都有所体会,在不同的项目可能会使用不同的Django版本,兼任性是大问题,如果不幸要去接手不同版本的项目,比较惨烈! 如果想重装一个Django版本,需要先卸载后安装。...

python处理document文档保留原样式

document文档格式、线段、图片、页眉页脚等都不变,供大家参考,具体内容如下 # -*- coding: utf-8 -*- # @Time : 2019/5/6 11:46...