import urllib.request ,sys
import re
def get_weather():
provice = input('输入省份名(请使用拼音):')
city = input('输入城市名(请使用拼音):')
#获取天气的URL
url = "http://qq.ip138.com/weather/"+provice+'/'+city+'_7tian.htm'
#获取页面信息
weatherhtml = urllib.request.urlopen(url);
res = weatherhtml.read().decode("GB2312");
#将获取信息写入
f=open('wea.txt','wb');
f.write(res.encode('GB2312'))
f.close()
#正则表达式获取天气信息
pattern = 'Title.+(.+)'
Title = re.search(pattern,res).group(1)
pattern = '>(\d*-\d*.+?)<'
date = re.findall(pattern,res)
pattern = 'alt="(.+?)"'
weather = re.findall(pattern,res)
print("%35.30s"%Title)
length = len(date)
for i in range(0,length):
print('%33.20s'%date[i],'\t%s'%weather[i])
if __name__=="__main__":
get_weather()
代码参考:获取未来七天天气情况