利用 Python 从互联网公开服务中获取天气预报信息。天气信息来源网站:
http://www.webxml.com.cn/WebServices/WeatherWebService.asmx
实现以下函数:
(1)获取支持城市:
函数原型: def get_support_city(province)
参数 province:字符串,省份名称,如“陕西”
返回值:字典类型,Key 为城市名称,Value 为城市代码;如:{'西安': '57036', '韩城': '53955',
'安康': '57245', '汉中': '57127', '宝鸡': '57016''}
提示:采用 getSupportCity 服务。
(2)获取天气:
函数原型: def get_weather(name)
参数 name:字符串,城市名称。
返回值:字符串,网站返回记录中的“今日天气实况”内容,如“今日天气实况:气温:
3℃;风向/风力:西北风 2 级;湿度: 66%;紫外线强度:最弱。空气质量:中。”
提示:采用 getWeatherbyCityName 服务。
参考网站:
https://blog.csdn.net/cw123458945/article/details/8146984
http://www.webxml.com.cn/WebServices/WeatherWebService.asmx
Web 可编程资源
http://www.programmableweb.com/
#!/usr/bin/python
# -*- coding: UTF-8
import json
import urllib.request
from urllib.parse import quote
import string
from xml.dom import minidom
#12.获取当前天气情况
#(1)获取支持城市
def get_support_city(province):
pass
url = 'http://www.webxml.com.cn/WebServices/WeatherWebService.asmx/getSupportCity?byProvinceName='+province
url = quote (url, safe=string.printable)
ret=urllib.request.urlopen(url)
txt=ret.read().decode('utf-8')
string_str=''
key_value=''
key_value_list=[]
word_flag=0
# print (txt)
for i in txt:
string_str += i
# print(string_str)
if string_str.replace(' ','').replace('\t','').replace('\n','').replace('\r','')== '':
# print ('---------------------------string_str')
word_flag = 1
if i=='>':
string_str=''
if word_flag==1:
key_value+=i
# print(key_value,'*************************************')
else:
key_value=''
if i=='<' and word_flag==1:
key_value_list.append(key_value.replace('<','').replace('>','').replace('(','').replace(')',''))
key_value=''
word_flag=0
# print(key_value_list)
support_city={}
for i in key_value_list:
# print(i)
word=i.split(' ')
support_city[word[0]]=word[1]
# print(support_city)
return support_city
#(2)获取天气
def get_weather(name):
page = urllib.request.urlopen("http://www.webxml.com.cn/WebServices/WeatherWebService.asmx/getWeatherbyCityName?theCityName="+name)
lines = page.readlines()
page.close()
document = ""
for line in lines :
document = document + line.decode('utf-8')
from xml.dom.minidom import parseString
dom =parseString(document)
strings = dom.getElementsByTagName("string")
print ('今日天气实况:',strings[10].childNodes[0].data)
if __name__ == '__main__':
pass
province=input('请输入要查询的省份:')
province = quote (province, safe=string.printable)
support_city=get_support_city(province)
print(support_city)
name=input('请在上述城市中选择城市:')
# name = quote (name, safe=string.printable)
name=support_city[name]
city_weather = get_weather (name)