import urllib.request
#import html

def get_weather(localcode): 
    res="--------------------------\n" # storage weather information
    #print("get today's weather from http://www.weather.com.cn\n")
    url="http://www.weather.com.cn/weather/"+str(localcode)+".shtml"
    req=urllib.request.Request(url)

    f_str=urllib.request.urlopen(req).read().decode('utf-8')
    f1=str(f_str)

    f_on=f1.find("fc_24h_internal_update_time")
    f_off=f1.find("（明天）")
    f_today=f1[f_on:f_off]

    w1=f_today.find("wea")+5 #start position of today's weather
    w2=f_today.find("tem")-15 #end positon of today's weather
    f_tdw=f_today[w1:w2]
    #print(f_tdw)
    res=res+f_tdw+"  |  "
    
    t1=f_today.find("tem")+7 #start position of today's temperature
    t2=f_today.find("win")-20 #end positon of today's temperature
    f_tdt=f_today[t1:t2]
    #print("raw text on html of temperature:  "+f_tdt)
    #res=res+"raw text on html of temperature:  "+f_tdt+"\n"
    ctrl_1=f_tdt.find("</span>/<i>")
    if ctrl_1==-1:
        ctrl_1=f_tdt.find("i>")+2
        ctrl_2=f_tdt.find("℃")
        temp=f_tdt[ctrl_1:ctrl_2]+ " C "
    else:
        ctrl_2=ctrl_1+11
        tem_h=f_tdt[5:ctrl_1] #high temperature
        tem_l=f_tdt[ctrl_2:-1] #low tempterature
        temp=tem_l+" ~ "+tem_h +" C "
    #print(temp)
    res=res+temp+"\n==========================\n"
    return res

if __name__=="__main__":    
    print("+----------------------+")
    print("|---weather get v1.0---|")
    print("+----------------------+")
    print("get today's weather from http://www.weather.com.cn\n")
    weathermartrix=[
    ["天津","101030100",""],
    ["北京",101010100,""],
    ["上海",101020100,""],
    ["内蒙古呼和浩特",101080101,""],
    ["安徽淮南",101220401,""],    
    ]
    
    for i in range(0,len(weathermartrix)):
        weathermartrix[i][2]=get_weather(weathermartrix[i][1])
        print(weathermartrix[i][0])
        print(weathermartrix[i][2])
    
    

