Python3 XML 获取雅虎天气的实现方法
作者:mabing993 时间:2023-02-13 16:35:38
参考廖雪峰的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))
来源:http://blog.csdn.net/mabing993/article/details/79210096
标签:Python3,XML,雅虎,天气
0
投稿
猜你喜欢
去掉运行JavaScript时IE产生的警告栏
2008-09-11 18:07:00
分享一个超好用的php header下载函数
2023-09-03 21:31:43
MySQL中分页优化的实例详解
2024-01-27 03:46:35
在Python中操作字典之clear()方法的使用
2021-10-02 15:57:38
ajax框架:ExtJs简介
2008-09-02 16:51:00
Python中的条件判断语句基础学习教程
2021-06-19 11:51:36
javascript代码实现简易计算器
2024-04-16 08:57:46
python基础之函数
2022-11-08 16:23:47
批量更新数据库所有表中字段的内容,中木马后的急救处理
2024-01-27 21:19:54
Dreamweaver使用快技法十三则
2009-07-21 12:45:00
基于python使MUI登录页面的美化
2023-10-23 16:28:03
python playwrigh框架入门安装使用
2023-05-07 23:18:51
Python实现简单求解给定整数的质因数算法示例
2021-05-27 09:23:08
DBCC CHECKIDENT 重置数据库标识列从某一数值开始
2024-01-15 11:16:27
asp如何做一个看他爱不爱你的小测验?
2010-07-11 21:16:00
javascript中解析四则运算表达式的算法和示例
2024-04-28 09:41:37
Python中pandas dataframe删除一行或一列:drop函数详解
2021-07-09 16:46:47
python3.6使用tkinter实现弹跳小球游戏
2022-04-09 14:37:13
MySQL中随机生成固定长度字符串的方法
2024-01-12 13:04:20
在Vue框架中配置Mock服务器的方法
2024-04-28 09:27:38