参考廖雪峰的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" 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 获取雅虎天气的实现方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。
华山资源网 Design By www.eoogi.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
华山资源网 Design By www.eoogi.com
暂无评论...
更新日志
2024年11月20日
2024年11月20日
- 柏菲·珞叔作品集《金色大厅2》限量开盘母带ORMCD[低速原抓WAV+CUE]
- Gareth.T《sad songs(Explicit)》[320K/MP3][29.03MB]
- Gareth.T《sad songs(Explicit)》[FLAC/分轨][152.85MB]
- 证声音乐图书馆《海风摇曳·盛夏爵士曲》[320K/MP3][63.06MB]
- 龚玥《金装龚玥HQCD》头版限量[WAV分轨]
- 李小春《吻别》萨克斯演奏经典[原抓WAV+CUE]
- 齐秦《辉煌30年24K珍藏版》2CD[WAV+CUE]
- 证声音乐图书馆《海风摇曳·盛夏爵士曲》[FLAC/分轨][321.47MB]
- 群星 《世界经典汽车音乐》 [WAV分轨][1G]
- 冷漠.2011 《冷漠的爱DSD》[WAV+CUE][1.2G]
- 陈明《流金岁月精逊【中唱】【WAV+CUE】
- 群星《Jazz-Ladies1-2爵士女伶1-2》HQCD/2CD[原抓WAV+CUE]
- 群星《美女私房歌》(黑胶)[WAV分轨]
- 郑源.2009《试音天碟》24BIT-96KHZ[WAV+CUE][1.2G]
- 飞利浦试音碟 《环球群星监听录》SACD香港版[WAV+CUE][1.1G]