#!/usr/bin/python3 # -*- coding: UTF-8 -*- # 中国天气数据 from urllib.parse import quote import urllib.request import re #Domoticz服务器 domoticzserver = "127.0.0.1:2780" #今日天气idx today_idx = "29" #明日天气idx tomorrow_idx = "30" #地区编号,来源:http://www.weather.com.cn/weather/101120501.shtml area = "101180101" #此方法向Domoticz服务器发送请求 def domoticzrequest (url): response = urllib.request.urlopen(url) return response.read() ''' 七日预报 ''' weather_url = "http://www.weather.com.cn/weather/"+area+".shtml" weather_response = urllib.request.urlopen(weather_url) weather_result = weather_response.read().decode('utf-8') # 七日预报结果 # 天气,weathers[0-6] weathers = re.findall(u'title="(.*)" class="wea">',weather_result) # 高低温度,temps[0-6][0-1] #temps = re.findall(u'(\d+)/(\d+)',weather_result) temps = re.findall(u'
\n(?:(-?\d+).*/)?(-?\d+)',weather_result) #今日,weathers[0] today_url = "http://"+domoticzserver+"/json.htm?type=command¶m=udevice&idx="+today_idx+"&nvalue=0&svalue="+weathers[0]+","+(temps[0][0]+"/" if temps[0][0]!='' else "")+temps[0][1]+"℃" domoticzrequest(quote(today_url, safe='/:?=&')) #明日,weathers[1] tomorrow_url = "http://"+domoticzserver+"/json.htm?type=command¶m=udevice&idx="+tomorrow_idx+"&nvalue=0&svalue="+weathers[1]+","+temps[1][0]+"/"+temps[1][1]+"℃" domoticzrequest(quote(tomorrow_url, safe='/:?=&'))