python查天气预报_python获取当前天气情况

利用 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.获取当前天气情况

群号:733065427

#(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)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值