未加星标

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

字体大小 | |
[开发(python) 所属分类 开发(python) | 发布者 店小二04 | 时间 | 作者 红领巾 ] 0人收藏点击收藏

参考廖雪峰的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实现从百度API获取天气的方法Python获取任意xml节点值的方法

本文开发(python)相关术语:python基础教程 python多线程 web开发工程师 软件开发工程师 软件开发流程

主题: XMLPythonLinux百度
tags: weather,forecast,city,name,attrs,url,flag,date,file,text,data,print,parser
分页:12
转载请注明
本文标题:Python3 XML 获取雅虎天气的实现方法
本站链接:https://www.codesec.net/view/572287.html


1.凡CodeSecTeam转载的文章,均出自其它媒体或其他官网介绍,目的在于传递更多的信息,并不代表本站赞同其观点和其真实性负责;
2.转载的文章仅代表原创作者观点,与本站无关。其原创性以及文中陈述文字和内容未经本站证实,本站对该文以及其中全部或者部分内容、文字的真实性、完整性、及时性,不作出任何保证或承若;
3.如本站转载稿涉及版权等问题,请作者及时联系本站,我们会及时处理。
登录后可拥有收藏文章、关注作者等权限...
技术大类 技术大类 | 开发(python) | 评论(0) | 阅读(96)