#!/uer/bin/env python # encoding: utf-8 import re import urllib2 import time def getHtml(url): page = urllib2.urlopen(url) mybytes = page.read() html = mybytes.decode("utf8") page.close() return html def getWeather(html): reg = r'<a title=.*?>(.*?)</a>.*?' reg += r'<img.*?alt="(.*?)".*?' reg += r'<img.*?alt="(.*?)".*?' reg += r'<span>(.*?)</span>.*?<b>(.*?)</b>' weatherList = re.compile(reg).findall(html) return weatherList while 1: adress = raw_input("請輸入須要查詢的省市的拼音全寫(shanghai):") weatherList = getWeather(getHtml(r"http://www.weather.com.cn/%s/index.shtml" %adress)) for weather in weatherList : print '%s,PM:%s/AM:%s %s/%s' %(format(weather[0]),format(weather[1]),format(weather[2]),format(weather[3]),format(weather[4])) print '\n' result = raw_input("are you want close?") if result == 'y' or result == 'Y': break
運行結果:html
請輸入須要查詢的省市的拼音全寫(shanghai):shanghaipython
上海,PM:多雲轉晴/AM:多雲轉晴 29℃/21℃url
寶山,PM:晴/AM:晴 28℃/21℃spa
嘉定,PM:晴/AM:晴 29℃/21℃code
崇明,PM:晴/AM:晴 28℃/19℃orm
奉賢,PM:多雲轉晴/AM:多雲轉晴 26℃/21℃htm
浦東南匯,PM:多雲轉晴/AM:多雲轉晴 27℃/19℃utf-8
浦東,PM:多雲轉晴/AM:多雲轉晴 28℃/20℃get
金山,PM:多雲轉晴/AM:多雲轉晴 27℃/20℃input
青浦,PM:多雲轉晴/AM:多雲轉晴 29℃/20℃
松江,PM:多雲轉晴/AM:多雲轉晴 29℃/21℃
閔行,PM:多雲轉晴/AM:多雲轉晴 29℃/21℃
徐家彙,PM:多雲轉晴/AM:多雲轉晴 29℃/21℃
are you want close?