Python3 XML 獲取雅虎天氣的實現(xiàn)方法
更新時間:2018年02月01日 09:31:09 作者:mabing993
下面小編就為大家分享一篇Python3 XML 獲取雅虎天氣的實現(xiàn)方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
參考廖雪峰的Python教程,實現(xiàn)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 獲取雅虎天氣的實現(xiàn)方法就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
使用Python實現(xiàn)正態(tài)分布、正態(tài)分布采樣
今天小編就為大家分享一篇使用Python實現(xiàn)正態(tài)分布、正態(tài)分布采樣,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-11-11Python函數(shù)式編程模塊functools的使用與實踐
本文主要介紹了Python函數(shù)式編程模塊functools的使用與實踐,教你如何使用?functools.partial、functools.wraps、functools.lru_cache?和?functools.reduce,感興趣的可以了解一下2024-03-03Python實現(xiàn)批量將符合要求的文件自動復(fù)制到新文件夾
這篇文章主要為大家詳細(xì)介紹了如何使用Python實現(xiàn)批量將文件名稱符合要求的文件自動復(fù)制到新文件夾,文中的示例代碼講解詳細(xì),有需要的小伙伴可以參考下2023-10-10Pycharm使用Conda激活環(huán)境失敗的問題解決
本文主要介紹了Pycharm使用Conda激活環(huán)境失敗的問題解決,文中主要介紹了兩種問題的解決,具有一定的參考價值,感興趣的可以了解一下2023-09-09python+opencv邊緣提取與各函數(shù)參數(shù)解析
這篇文章主要介紹了python+opencv邊緣提取與各函數(shù)參數(shù)解析,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-03-03